【问题标题】:Translate unsigned char *buf=NULL to Pascal?将 unsigned char *buf=NULL 转换为 Pascal?
【发布时间】:2011-12-19 10:50:14
【问题描述】:

我在 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.

【问题讨论】:

  • 1) unsigned char = Byte,而不是 Char(责备 Ritchie),2) new 可以转换为 GetMem(&lt;integral sizeof&gt;) 或声明大小为 3 的中间类型) for 循环很简单

标签: c++ delphi char translate pchar


【解决方案1】:

大概是这样的:

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];

【讨论】:

  • 我可以用 AnsiChar 数组代替 Byte 数组吗?
  • 它们几乎可以互换。但是,如果您想将其视为PAnsiChar,那么您需要一个演员表。我怀疑使用Byte 而不是AnsiChar 没有什么好处。
  • 动态数组只会让事情变得更糟,PChar^PByte^ 已经是数组了(顺便说一句,这是 C++,不是 C)
  • @premature 你在说什么?动态数组有什么问题?它们与 C++ new[] 非常匹配。您建议从哪里获取缓冲区?
【解决方案2】:

其实在:

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;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-10-19
    • 2013-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-18
    相关资源
    最近更新 更多