从 Native 指针中获取数据

2024-01-31

将数据放入 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 https://docs.perl6.org/routine/nativecast显然是在相反的方向上工作,或者至少不是在转换为非本地类型的方向上(从名字上应该很明显)。你会怎么做?

Update:例如,使用数组会使其更可行。然而

my $inter = nativecast(CArray[int16], $dest);
.say for $inter.list;

这有效,但会产生错误:Don't know how many elements a C array returned from a library

Update 2: 下列的克里斯托夫的回答 https://stackoverflow.com/a/51083251(谢谢!),我们可以进一步详细说明这一点,然后我们可以将这些值放回Buf https://docs.perl6.org/type/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;

我们需要将指针转换为与缓冲区使用的类型完全相同的类型,然后我们使用指针算术 https://docs.perl6.org/language/nativecall#Typed_Pointers跑过去。然而,我们使用$blob.bytes知道何时结束循环,但这仍然有点棘手。有没有更直接的方法呢?或者只是一种使用 Bufs/Blob 的方法,以便可以轻松地将它们复制到本机领域并返回?


完整示例:

use NativeCall;

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(nativesizeof(int16));
memcpy($dest, $src, nativesizeof(int16));
my $inter = nativecast(Pointer[int16], $dest);
say $inter.deref.fmt('%x');

我假设您正在寻找deref方法,但您的代码还存在一些其他问题:

  • use of int32代替size_t在声明中memcpy
  • 参数的顺序错误memcpy,这意味着您将从未初始化的内存中读取的两个字节复制到您所谓的不可变的 Blob 中
  • 使用普通的int您可能应该使用大小整数类型,例如int16

还要注意使用普通Pointer在声明中memcpy,这将允许您传入任何指针类型,而不必不断进行强制转换。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

从 Native 指针中获取数据 的相关文章

随机推荐