HiroH
Denoβ€’3y agoβ€’
9 replies
Hiro

Pass string to struct FFI

Quick question about Struct-Value feature, what would be the best way to pass *const u8 (or strings) to structs?
I am kinda lost after reading the tests to get some examples running, here's what I got working so far :
const lib = Deno.dlopen("./target/debug/libtest_struct.so", {
    add: {
        parameters: [{struct: ["buffer"] }],
        result: "void"
    }
})

const buff1 = new TextEncoder().encode("Hello\0").buffer

const ptr = Deno.UnsafePointer.of(buff1);
const struct = new BigUint64Array([BigInt(ptr)]);

lib.symbols.add(struct)


use std::ffi;

#[derive(Debug)]
#[repr(C)]
pub struct Point {
    pub test: *const u8,
}


#[no_mangle]
pub extern "C" fn add(points: Point) {
    let ptr = points.test;
    let strtest = unsafe { ffi::CStr::from_ptr(ptr as *const i8) };
    println!("strtest: {:?}", strtest);
}


There must be a beter way of doing this right?
Was this page helpful?