【发布时间】:2018-06-28 11:13:35
【问题描述】:
将数据放入 Perl 6 Native 指针中没什么大不了的:
sub memcpy( Pointer[void] $source, Pointer[void] $destination, int32 $size ) is native { * };
my Blob $blob = Blob.new(0x22, 0x33);
my Pointer[void] $src-memcpy = nativecast(Pointer[void], $blob);
my Pointer[void] $dest-memcpy = malloc( 32 );
memcpy($src-memcpy,$dest-memcpy,2);
my Pointer[int] $inter = nativecast(Pointer[int], $dest-memcpy);
say $inter; # prints NativeCall::Types::Pointer[int]<0x4499560>
但是,除了创建一个函数来执行此操作之外,我认为没有办法让它们脱离 Pointer[int],因为 nativecast 显然在相反的方向上工作,或者至少不是在强制转换为非本机类型(其名称应该很明显)。你会怎么做?
更新:例如,使用数组会使其更可行。不过
my $inter = nativecast(CArray[int16], $dest);
.say for $inter.list;
这可行,但会产生错误:Don't know how many elements a C array returned from a library
更新 2:在 Christoph's answer(谢谢!)之后,我们可以对此进行更详细的阐述,我们可以将值放回 Buf
sub malloc(size_t $size --> Pointer) is native {*}
sub memcpy(Pointer $dest, Pointer $src, size_t $size --> Pointer) is native {*}
my $blob = Blob.new(0x22, 0x33);
my $src = nativecast(Pointer, $blob);
my $dest = malloc( $blob.bytes );
memcpy($dest, $src, $blob.bytes);
my $inter = nativecast(Pointer[int8], $dest);
my $cursor = $inter;
my Buf $new-blob .= new() ;
for 1..$blob.bytes {
$new-blob.append: $cursor.deref;
$cursor++;
}
say $new-blob;
我们需要将指针转换为缓冲区使用的完全相同的类型,然后we use pointer arithmetic 运行它。但是,我们使用$blob.bytes 来知道何时结束循环,它仍然有点hacky。有没有更直接的方法?或者只是一种使用 Bufs/Blob 的方式,以便可以轻松地将它们复制到 Native 领域并返回?
【问题讨论】:
标签: raku nativecall