将 unsigned char *buf=NULL 转换为 Pascal?

发布于 12-12 18:49 字数 333 浏览 1 评论 0原文

我在 Borland Delphi 中工作,并且在 Borland C++ Builder 中有几行代码。我想将这些行翻译成 Delphi 源代码。

unsigned char *buf=NULL;
buf=new unsigned char[SPS*2];
for (i=0; i<SPS*2; i++)
   buf[i]=2;

... ....

answers=buf[2];

我想用这个buf分配一个PCHar值;

a:PCHar;
a:=buf.

I'm working in Borland Delphi, and i have a few lines code in Borland C++ Builder. I would like to translate these lines into Delphi source.

unsigned char *buf=NULL;
buf=new unsigned char[SPS*2];
for (i=0; i<SPS*2; i++)
   buf[i]=2;

...
....

answers=buf[2];

I would like to assign a PCHar value with this buf;

a:PCHar;
a:=buf.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

恏ㄋ傷疤忘ㄋ疼2024-12-19 18:49:26

事实上,在:

unsigned char *buf=NULL;
buf=new unsigned char[SPS*2];

第一个赋值 *buf=NULL 可以翻译为 buf := nil 但它是纯粹的死代码,因为 buf指针内容立即被new函数覆盖。

因此,您的 C 代码可能会被翻译为:

var buf: PAnsiChar;
    i: integer;
begin
  Getmem(buf,SPS*2);
  for i := 0 to SPS*2-1 do
    buf[i] := #2;
...
  Freemem(buf);
end;

更符合 Delphi 习惯的版本可能是:

var buf: array of AnsiChar;
    i: integer;
begin
  SetLength(buf,SPS*2);
  for i := 0 to high(buf) do
    buf[i] := #2;
  ...
  // no need to free buf[] memory (it is done by the compiler)
end;

或直接:

var buf: array of AnsiChar;
    i: integer;
begin
  SetLength(buf,SPS*2);
  fillchar(buf[0],SPS*2,2);
  ...
  // no need to free buf[] memory (it is done by the compiler)
end;

In fact, in:

unsigned char *buf=NULL;
buf=new unsigned char[SPS*2];

The first assignment *buf=NULL can be translated as buf := nil but it is pure dead code, since buf pointer content is immediately overwritten by the new function.

So your C code may be translated as such:

var buf: PAnsiChar;
    i: integer;
begin
  Getmem(buf,SPS*2);
  for i := 0 to SPS*2-1 do
    buf[i] := #2;
...
  Freemem(buf);
end;

A more Delphi-idiomatic version may be:

var buf: array of AnsiChar;
    i: integer;
begin
  SetLength(buf,SPS*2);
  for i := 0 to high(buf) do
    buf[i] := #2;
  ...
  // no need to free buf[] memory (it is done by the compiler)
end;

or directly:

var buf: array of AnsiChar;
    i: integer;
begin
  SetLength(buf,SPS*2);
  fillchar(buf[0],SPS*2,2);
  ...
  // no need to free buf[] memory (it is done by the compiler)
end;
一影成城2024-12-19 18:49:26

也许是这样的:

var
  buf: array of AnsiChar;
  a: PAnsiChar;
...
SetLength(buf, SPS*2);
FillChar(buf[0], Length(buf), 2);
a := @buf[0];

不知道 answers 是什么,但是,假设它是 C++ 代码中的 char 那么你会这样写:

var
  answers: AnsiChar;
...
answers := buf[2];

Perhaps like this:

var
  buf: array of AnsiChar;
  a: PAnsiChar;
...
SetLength(buf, SPS*2);
FillChar(buf[0], Length(buf), 2);
a := @buf[0];

No idea what answers is, but, assuming it is a char in your C++ code then you would write it like this:

var
  answers: AnsiChar;
...
answers := buf[2];
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文