gpt4 book ai didi

raku - NativeCall 中的位域

转载 作者:行者123 更新时间:2023-12-04 08:01:45 32 4
gpt4 key购买 nike

我正在尝试为 Cgraph 创建 Perl6 绑定(bind),其中一个结构为其某些属性设置了位字段,其值低于 8。我应该如何在我的模块中表示它?

我尝试使用 is nativesize(x) 定义自定义类型trait,但 CStructs 仅支持 8 位宽的倍数的类型。

C 示例代码:

struct Agtag_s {
unsigned objtype:2;
}

我尝试了什么:
my native objtype is repr('P6int') is Int is nativesize(2) is export { }
class Agtag is repr('CStruct') is export {
has objtype $.object-type;
}

尝试将我的模块与该代码一起使用失败并显示以下错误消息: CStruct only supports native types that are a multiple of 8 bits wide (was passed: 2)

最佳答案

这是一个例子。我假设一个函数 use_struct()在库中定义 libslib :

#include <stdio.h>

struct Agtag_s {
unsigned objtype:2;
unsigned footype:4;
unsigned bartype:6;
};

void use_struct (struct Agtag_s *s) {
printf("sizeof(struct Agtag_s): %ld\n", sizeof( struct Agtag_s ));
printf("objtype = %d\n", s->objtype);
printf("footype = %d\n", s->footype);
printf("bartype = %d\n", s->bartype);
s->objtype = 3;
s->footype = 13;
s->bartype = 55;
}

然后在 Perl 6 中:
use v6;
use NativeCall;

class Agtag is repr('CStruct') is export {
has int32 $.bitfield is rw;
}

sub use_struct(Agtag $s is rw) is native("./libslib.so") { * };

my $s = Agtag.new();
my $objtype = 1;
my $footype = 7;
my $bartype = 31;
$s.bitfield = $objtype +| ($footype +< 2 ) +| ($bartype +< 6);
say "Calling library function..";
say "--------------------------";
use_struct( $s );
say "After call..";
say "------------";
say "objtype = ", $s.bitfield +& 3;
say "footype = ", ($s.bitfield +> 2) +& 15;
say "bartype = ", ($s.bitfield +> 6) +& 63;

输出 :
Calling library function..
--------------------------
sizeof(struct Agtag_s): 4
objtype = 1
footype = 7
bartype = 31
After call..
------------
objtype = 3
footype = 13
bartype = 55

关于raku - NativeCall 中的位域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56775926/

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