CStruct中声明一个数组

CStruct中声明一个数组

本文介绍了在Perl 6 NativeCall CStruct中声明一个数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在CStruct中声明对象数组?

Is there any way to declare an array of objects inside a CStruct?

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

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

A CArray [uint8] 将是一个 char * 指针,而不是实际上在结构内部保留空间。

A CArray[uint8] would be a char * pointer, not actually reserving space inside the struct.

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

Instead of My::Struct.new, I could probably make the memory myself (instead of My::Struct.new(), I use a buf8.allocate(xxx) and keep a handle so the GC doesn't reap it, nativecast it to My::Struct), then I have to use pointer math to find the string inside the struct, etc. but it seems like there should be an easier way.

甚至如果尚未完全实现,则说在此处放置80个字节,这是它的指针的简单方法将非常好。

Even if it wasn't fully implemented, a simple way to say "Put 80 bytes here and here's a Pointer to it" would be very nice.

推荐答案

这是我的丑陋解决方法:

Here is my ugly work-around:

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);
    }
}

这篇关于在Perl 6 NativeCall CStruct中声明一个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 17:35