Raku 如何将指向 Buf 的指针传递给本地调用以进行写入

Raku how to pass a pointer to a Buf to a native call for writing

我正在尝试包装 unistd.h 中的 read 函数,但无法使其正常工作。 这是我所拥有的:(在文件中: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)

好的,所以问题出在 Pointer $bufrw 特征上。我猜这会导致 read 函数在写入时递增指针,因此在我稍后使用它时会给出错误的地址。

这是两种情况下的工作代码:

use NativeCall;

# ssize_t read(int fd, void *buf, size_t count);

sub c_read(int32 $fd, Pointer $buf, size_t $count --> ssize_t) is native is symbol('read') { * }


# Passing a pointer to a Buf directly:
{
    my $buf = Buf[byte].new(0 xx 5);
    my $pbuf = nativecast(Pointer[byte], $buf);
    say c_read(3, $pbuf, 5);
    say '---------------------';
    say $buf;

}


# Using malloc also works:
{
    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];
}

这样测试的:

$ (exec 3< <(echo hello world); perl6  ./read.raku)
5
---------------------
Buf[byte]:0x<68 65 6C 6C 6F>
5
---------------------
(32 119 111 114 108)