gpt4 book ai didi

arrays - 在 Perl 6 NativeCall CStruct 中声明一个数组

转载 作者:行者123 更新时间:2023-12-04 12:16:37 25 4
gpt4 key购买 nike

有没有办法在 CStruct 中声明一个对象数组?

struct my_struct {
int foo;
int bar;
char somestring[80];
};

class My::Struct is repr('CStruct') {
has int32 $.foo;
has int32 $.bar;
???
}

一个 CArray[uint8]将是 char *指针,实际上并没有在结构内保留空间。

而不是 My::Struct.new ,我可能可以自己制作内存(而不是 My::Struct.new() ,我使用 buf8.allocate(xxx) 并保留一个句柄,以便 GC 不会收获它, nativecast 将它交给 My::Struct),然后我必须使用指针数学在结构中查找字符串等,但似​​乎应该有更简单的方法。

即使它没有完全实现,一个简单的方法说“把 80 个字节放在这里,这里有一个指向它的指针”会非常好。

最佳答案

这是我丑陋的解决方法:

class My::Struct is repr('CStruct') {
has int32 $.foo is rw;
has int32 $.bar is rw;
has int64 $.h0; # 10 int64s = 80 bytes
has int64 $.h1;
has int64 $.h2;
has int64 $.h3;
has int64 $.h4;
has int64 $.h5;
has int64 $.h6;
has int64 $.h7;
has int64 $.h8;
has int64 $.h9;

method somestring {
nativecast(Str, Pointer.new(nativecast(Pointer, self)+8))
}

sub strcpy(Pointer, Blob, --> Pointer) is native {}

method set-somestring(Str:D $s) {
my $buf = "$s\0".encode;
die "too long" if $buf.bytes > 80;
strcpy(Pointer.new(nativecast(Pointer, self)+8), $buf);
}
}

关于arrays - 在 Perl 6 NativeCall CStruct 中声明一个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48646159/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com