How to pass a Perl 6 object through a Nativecall callback?

I work with the NativeCall interface.

The library will call my callback function a bunch of times.

It works great. I can simply declare my signature callback, pass it as a callback, and the library calls well.

It also has the ability to set the payload void * pointer to anything I want, and it will include this in a call to my callback function.

Is it possible to hide Perl Str, for example, in a payload and successfully bypass it?

sub set_userdata(Pointer) returns int32 is native { ... } sub set_callback(&callback(Pointer $userdata --> int32)) returns int32 is native { ... } sub callback(Pointer $userdata) returns int32 { my Str $mystring = ??? ... } my Str $my-userdata-string; set_userdata(???); set_callback(&callback); 

It looks like it could work with some binding spell, "this is rw", nativecast () and / or .deref.

+5
source share
2 answers

In this case, you can only use your own view (for example, CStruct , CArray and CPointer ), or, alternatively, Blob . You are also responsible for keeping a reference to what you pass as userdata live from the point of view of Perl 6, so GC does not return the memory that was passed to C.

Memory management is the reason that you cannot pass any old Perl 6 object to the C function: there is no way for the GC to find out if the object is still accessible through some C data structure that it cannot examine. In a VM, like MoarVM objects, they move in memory over time as part of the garbage collection process, which means that C code may end with an obsolete pointer.

An alternative strategy is not to pass a pointer in general, but instead pass an integer and use it to index into an array of objects. (The way libuv binding inside MoarVM tracks VM level callbacks, fwiw.)

+7
source

I got around this by simply ignoring user data and creating a new closure that references the Perl object directly for each callback function. Since there is a new closure created every time I set up a callback, I think this memory leaks over time.

+2
source

Source: https://habr.com/ru/post/1266649/


All Articles