gpt4 book ai didi

arrays - 结构数组作为Perl 6 NativeCall结构的属性

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

我正在尝试封装一个C结构,其中一个成员是一个指向结构的指针的数组,并且在弄清楚如何做到这一点时遇到了问题。

假设C代码看起来像这样:

struct foo
{
unsigned char a;
};

struct bar
{
struct foo *f[5];
};

这种代码的工作原理是:
use NativeCall;

class foo is repr('CStruct') {
has uint8 $.a;
}

class bar is repr('CStruct') {
has foo $.f1;
has foo $.f2;
has foo $.f3;
has foo $.f4;
has foo $.f5;
}

但这太可怕了

此处的 CArray毫无用处,因为它只是指向数组的指针,而不是指针数组。我不能使用类似 has A @.a的东西,因为 repr('CStruct')不能处理这种属性。

有什么提示吗?

最佳答案

我为此编写了示例代码。
C面:

struct bar* create_bar_ptr(unsigned char a)
{
printf("GET A CHAR => %#0x = %c\n", a, a);

struct bar* bar = (struct bar*)malloc(sizeof(struct bar));

for (size_t i = 0;i < 5;i ++) {
struct foo* tf = (struct foo*)malloc(sizeof(struct foo));

tf->a = a + i;
bar->f[i] = tf;
}

printf("CREATE BAR PTR OK\n");

return bar;
}

由于Rakudo不支持从C端获取堆栈变量,因此应使用malloc在堆上分配 struct bar

然后使用gcc编译代码,例如 gcc -shared -fPIC -o libshasa.so xxx.c

这是Perl6的一面:

use NativeCall;

class foo is repr('CStruct') {
has uint8 $.a;
}

class bar is repr('CStruct') {
# Here you should use !!HAS!!, not has
HAS Pointer[foo] $.f1;
HAS Pointer[foo] $.f2;
HAS Pointer[foo] $.f3;
HAS Pointer[foo] $.f4;
HAS Pointer[foo] $.f5;
}


sub create_bar_ptr(uint8) returns Pointer[bar] is native('./libshasa.so') { * }

my Pointer[bar] $p = create_bar_ptr(uint8.new(97));

say $p.deref."f{$_}"().deref.a for 1 .. 5;

输出:
GET A CHAR => 0x61 = a
CREATE BAR PTR OK
97
98
99
100
101

关于arrays - 结构数组作为Perl 6 NativeCall结构的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44266457/

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