D
Deno

help

Update value by reference without duplicating the data

Jjavi1/17/2023
Im exploring the world of FFI, porting some C applications I have to TypeScript, with the help of Deno. Currently, I cannot think of an efficient way to update the value that a pointer is pointing to. For instance, in C I could do something like:
char **array = calloc(2, sizeof(char*));
if (array == NULL) return 1;
*(array) = "hello";
*(array + 1) = "world";
char **array = calloc(2, sizeof(char*));
if (array == NULL) return 1;
*(array) = "hello";
*(array + 1) = "world";
Nonetheless, with Deno I have to first either allocate memory with an allocator or create a TypedArray myself, then create a new unsafe pointer of that. To update it, I’d have to create an unsafe pointer view of that pointer, get the array buffer, create a new Uint8Array from that array buffer, use the <Uint8Array>.set function to update the chunk of memory, and then create a new unsafe pointer of that, duplicating the memory and adding extra complexity. Is there another way to do it? Thanks!
AAapoAlas1/17/2023
Uuuh... So I'm not exactly sure what you're trying to do but if you get a pointer from native code and want to assign a value to it, you can use Deno.UnsafePointerView.getArrayBuffer(pointer, byteLength) to get a readable and writable buffer of that pointer. Then you can use eg. new Uint8Array(buffer) or new DataView(buffer) to get a view into the buffer that can be used to actually read and write data into the buffer. None of this is copying data. Doing Deno.UnsafePointer.of(buffer) also does not copy data, it is just getting the pointer value (number) of a buffer or TypedArray.
AAapoAlas1/17/2023
If you need to write strings into an array of strings though, that's more complex since you'll need to keep the strings in memory while native code carries the array of pointers. Here's an example of how I've done this in one special case: https://github.com/aapoalas/libclang-deno/blob/main/lib/utils.ts#L10
GitHub
libclang-deno/utils.ts at main · aapoalas/libclang-deno
Deno FFI bindings for libclang. Contribute to aapoalas/libclang-deno development by creating an account on GitHub.
Jjavi1/18/2023
Great thanks , that answered my question <:hooray_deno:1035517542200004688>

Looking for more? Join the community!