首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在Perl 6 NativeCall CStruct中声明数组

在Perl 6 NativeCall CStruct中声明数组
EN

Stack Overflow用户
提问于 2018-02-06 23:11:28
回答 2查看 181关注 0票数 7

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

代码语言:javascript
复制
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中),然后我必须使用指针数学来查找结构中的字符串,等等,但似乎应该有一种更简单的方法。

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

EN

回答 2

Stack Overflow用户

发布于 2018-02-06 23:47:06

这是我丑陋的解决办法:

代码语言:javascript
复制
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);
    }
}
票数 5
EN

Stack Overflow用户

发布于 2020-06-14 16:20:31

稍后,here回答了这个问题。它使用"embedded“has == HAS声明一个本机元素数组,然后将该数组转换为CArray。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48646159

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档