Home > Blockchain >  How do I "assign" the value in `CArray` that contains a memory address to a `Pointer`?
How do I "assign" the value in `CArray` that contains a memory address to a `Pointer`?

Time:12-04

This is a NativeCall question.

I have 8 bytes (little endian) in a CArray representing a memory address. How do I create a Pointer out it?

(CArray and Pointer are two of NativeCall's C compatible types. Pointers are 8 bytes long. Things should line up, but how does one put the pointer address in a CArray into a Pointer in a way acceptable to NativeCall?)

CodePudding user response:

How do I create a Pointer out it?

I think you could use nativecast like this:

my $ptr = nativecast(CArray[Pointer], $array);
my Pointer $ptr2 = $ptr[$idx];

CodePudding user response:

From the comments it seems like the native sub should return a pointer to an array of struct. On linux I created the following example:

test.c

#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>

typedef struct myStruct
{
    int32_t A;
    double B;
} mstruct;

void set_pointer(mstruct **arrayOfStruct)
{
    mstruct *ptr = (mstruct *) malloc(sizeof(mstruct)*2);
    printf("allocated memory at address: %p\n", ptr);
    ptr[0].A = 10;
    ptr[0].B = 1.1;
    ptr[1].A = 20;
    ptr[1].B = 2.1;
    *arrayOfStruct = ptr;
}

p.raku:

use v6;
use NativeCall;

class myStruct is repr('CStruct') {
    has int32 $.A is rw;
    has num64 $.B is rw;
}

sub set_pointer(Pointer[CArray[myStruct]] is rw) is native("./libtest.so") { * };

my $array-ptr = Pointer[CArray[myStruct]].new();
set_pointer($array-ptr);
my $array = nativecast(Pointer[myStruct], $array-ptr.deref);
say $array[0].A;
say $array[0].B;
say $array[1].A;
say $array[1].B;

Output:

allocated memory at address: 0x5579f0d95ef0
10
1.1
20
2.1
  • Related