我正在尝试从 包装read
函数unistd.h
,但无法使其正常工作。这是我所拥有的:(在文件中read.raku
:)
use NativeCall;
# ssize_t read(int fd, void *buf, size_t count);
sub c_read(int32 $fd, Pointer $buf is rw, size_t $count --> ssize_t) is native is symbol('read') { * }
my $buf = Buf[byte].new(0 xx 5);
my $pbuf = nativecast(Pointer, $buf);
say c_read(3, $pbuf, 5);
say '---------------------';
say $buf;
我从命令行(bash)这样测试它:
$ (exec 3< <(echo hello world); raku ./read.raku)
但我得到:
5
---------------------
Buf[byte]:0x<00 00 00 00 00>
所以看起来从 FD 3 读取的字节没有写入Buf
.
我也试过这个:
use NativeCall;
# ssize_t read(int fd, void *buf, size_t count);
sub c_read(int32 $fd, Pointer $buf is rw, size_t $count --> ssize_t) is native is symbol('read') { * }
sub c_malloc(size_t $size --> Pointer) is native is symbol('malloc') { * }
my $pbuf = nativecast(Pointer[byte], c_malloc(5));
say c_read(3, $pbuf, 5);
say '---------------------';
say $pbuf[^5];
但是我遇到了分段错误,我猜是由于使用$pbuf[^5]
. 但即使只是$pbuf.deref
不给出读取的第一个字节。
所以我一定是做错了什么或者完全误解了如何使用本地调用。
更新:在玩了更多之后,看起来上面第二个片段的问题在于is rw
位。这似乎有效:
use NativeCall;
use NativeHelpers::Blob;
sub c_read(int32 $fd, Pointer $buf, size_t $count --> ssize_t) is native is symbol('read') { * }
sub c_malloc(size_t $size --> Pointer) is native is symbol('malloc') { * }
my $pbuf := nativecast(Pointer[byte], c_malloc(5));
say c_read(3, $pbuf, 5);
say '---------------------';
say $pbuf[^5]; # (104 101 108 108 111)