将结构数组传递给 Perl 6 NativeCall 函数 [英] Passing an array of structures to a Perl 6 NativeCall function
问题描述
我正在尝试使用 NativeCall 与一些 C 函数进行交互.
I'm trying to use NativeCall to interact with some C functions.
我有一个简单的 C 结构体和一个需要它们的数组的函数.
I have a simple C struct, and a function that wants an array of them.
struct foo {
int x;
char *s;
};
struct foo foo_array[3];
foo_array[0].x = 12;
foo_array[0].s = "foo";
foo_array[1].x = 27;
foo_array[1].s = "bar";
foo_array[2].x = -1;
void somefunc(foo_array);
我尝试了很多方法,但似乎无法完全正确.
I've tried a bunch of ways, but can't seem to get it quite right.
class foo is repr('CStruct') {
has int32 $.x;
has Str $.s
};
sub somefunc(CArray[foo]) is native { * }
my @foo-array := CArray[foo].new;
@foo-array[0] = ???
@foo-array[1] = ???
@foo-array[2] = ???
somefunc(@foo-array);
如何正确创建 foo 类的对象并设置它们的值,以及如何制作适合传递的数组?
How do I properly create an object of class foo and set their values, and how do I make an array of them suitable for passing?
推荐答案
据我所知,没有内置的方法可以做到这一点.但是,有足够的绳子可以上吊自己 建立一个解决方法:
As far as I'm aware, there's no built-in way to do this. However, there's enough rope to hang yourself build a workaround:
role StructArray[Mu:U \T where .REPR eq 'CStruct'] does Positional[T] {
has $.bytes;
has $.elems;
method new(UInt \n) {
self.bless(bytes => buf8.allocate(n * nativesizeof T), elems => n);
}
method AT-POS(UInt \i where ^$!elems) {
nativecast(T, Pointer.new(nativecast(Pointer, $!bytes) + i * nativesizeof T));
}
method pointer {
nativecast(Pointer[T], $!bytes);
}
}
这应该允许以下工作:
my @foo-array := StructArray[foo].new(10); # 'array' with 10 elements
@foo-array[0].x = 42;
通过将 @foo-array.pointer
传递给 Pointer[foo]
类型的参数,可以与 C 函数进行交互.由于结构也是通过指针传递的,您也可以将 @foo-array[0]
传递给 foo
类型的参数以获得相同的效果.
Interaction with C functions is possible by passing @foo-array.pointer
to a parameter of type Pointer[foo]
. As structures are passed by pointer as well, you could also pass @foo-array[0]
to a parameter of type foo
for the same effect.
这篇关于将结构数组传递给 Perl 6 NativeCall 函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!