#FFI Pointers

9 messages · Page 1 of 1 (latest)

blissful jay
#

Suppose I have the following C function

void get_len(const char* s, int32_t* len);

how do I use it via the Deno FFI. How does I pass the len pointer param and read its value back

gloomy thicket
#

First of all create a shared library of the C source. In your ts file open the library and declare the type (I’ve used i64 because it fits for this demo). Then encode the string into a Uint8Array and get the pointer of that. Allocate memory for the number (4 bytes since it’s int32_t) and get the pointer of that. Then just call the function. In order to check the value you’ll need to do an unsafe pointer view and get the int32 at offset 0

chrome field
#

Starting from Deno 1.31 pointers are no longer numbers as well, so the proposed "i64" will not work in the new release.

blissful jay
#

ty

gloomy thicket
#

until that release they were interchangeable

chrome field
# gloomy thicket until that release they were interchangeable

For the most part, yes. Although I've at least gotten a fun segfault with using the top bits of a void* user data pointer: I don't think any code on the native side was ever accessing though the pointer (since I wrote the native code myself as well, it was just a userdata parameter in a callback. Still, some presumably compiler injected check was validating the pointerness of the number.

gloomy thicket