#FFI Pointers
9 messages · Page 1 of 1 (latest)
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
Instead of "i64" you should use "pointer" and instead of "pointer" in this case you should use "buffer":
const dylib = Deno.dlopen(libName, {
get_len: { parameters: ["buffer", "buffer"], result: "void" },
});
const str = new TextEncoder().encode("hello\0");
const nb = new Uint8Array(4);
dylib.symbols.get_len(str, nb);
console.log(new Uint32Array(nb.buffer)[0]);
Starting from Deno 1.31 pointers are no longer numbers as well, so the proposed "i64" will not work in the new release.
ty
until that release they were interchangeable
Thanks for the heads up
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.
If I ever reach that point I’ll descend into madness. Thanks for the response 