如何解决C到Delphi很短
StructBox_s *pStructBox; // -> pStructBox: ^StructBox_s
int value = pStructBox[11].value; // ???
无法转换为Delphi代码。 “ pSturctBox [11] .value”
解决方法
是的,pStructBox: ^StructBox_s
在C / C ++中相当于StructBox_s *pStructBox;
的Delphi。通常使用类型别名来简化^
语法的使用。
C / C ++代码正在做的事情是将指针视为StructBox_s
实例数组的地址,访问该数组的第11个元素的value
成员。您显示的代码片段没有显示如何为该指针分配该数组地址。可以给它分配一个局部变量,一个全局变量,一个类成员,一个动态数组的地址,有很多不同的方法。但是在指针上应用[]
运算符的结果是相同的-访问一个StructBox_s
实例,该实例距离指针所指向的地址11 * sizeof(StructBox_s)
个字节。
在Delphi中,为了像C / C ++代码一样索引类型化的指针,可以在要索引的指针范围内启用{$POINTERMATH}
指令。
您可以在声明用于指针的 type 时启用指令,例如:
type
{$POINTERMATH ON}
PStructBox_s = ^StructBox_s;
StructBox_s = record
...
value: Integer;
...
end;
...
var
pStructBox: PStructBox_s;
value: Integer;
begin
...
pStructBox := ...; // <-- set to the address of some array of 12+ StructBox_s instances in memory...
value := pStructBox[11].value;
...
end;
或者,在执行实际索引的代码中启用指令:
type
PStructBox_s = ^StructBox_s;
StructBox_s = record
...
value: Integer;
...
end;
...
{$POINTERMATH ON}
var
pStructBox: PStructBox_s;
value: Integer;
begin
...
pStructBox := ...; // <-- set to the address of some array of 12+ StructBox_s instances in memory...
value := pStructBox[11].value;
...
end;
也就是说,如果您使用的是没有{$POINTERMATH}
指令的较旧版本的Delphi,则可以通过手动将指针增加到所需的偏移量来实现相同的结果,例如:
type
PStructBox_s = ^StructBox_s;
StructBox_s = record
...
value: Integer;
...
end;
...
var
pStructBox,pElem: PStructBox_s;
value: Integer;
begin
...
pStructBox := ...; // <-- set to the address of some array of 12+ StructBox_s instances in memory...
pElem := pStructBox;
Inc(pElem,11);
value := pElem^.value;
...
end;
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。