Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Decode makes my programme crash #138

Open
hanako-eo opened this issue Feb 22, 2024 · 3 comments
Open

Decode makes my programme crash #138

hanako-eo opened this issue Feb 22, 2024 · 3 comments

Comments

@hanako-eo
Copy link

hanako-eo commented Feb 22, 2024

I use koffi in a project and I have a function this function (it's in rust) :

#[no_mangle]
pub extern "C" fn get_headers<'a>(req: *const Request<'a>) -> *const (*const c_char, *const c_char) {
    let req = unsafe { &*req };
    // CString is just a equivalent to &[u8] store in the heap
    req.headers().as_ptr() as *const (*const c_char, *const c_char)
}

in c my function is equivalent to

typedef struct TupleString2 {
    char *first;
    char *last;
} TupleString2;
TupleString2 *get_headers(Request *req);

but want I try to do :

const StringTuple2 = koffi.struct({
    first: "char*",
    last: "char*"
})

const rust_get_headers = lib.func("get_headers", koffi.pointer(StringTuple2), [koffi.pointer(koffi.opaque("Request"))])

// req is generated in rust and pass to the javascript
console.log(koffi.decode(rust_get_headers(req), StringTuple2, 2))

My programme crash. Did I do something wrong with the decode?

@hanako-eo hanako-eo changed the title Decode error ? Decode makes my programme crash Feb 22, 2024
@Koromix
Copy link
Owner

Koromix commented Feb 22, 2024

In the koffi.decode() call, you are trying to decode an array of tuples (two, actually), instead of just one.

This works for me:

// gcc -shared -o 138.so -O2 -Wall 138.c

typedef struct Request {
    int dummy;
} Request;

typedef struct TupleString2 {
    char *first;
    char *last;
} TupleString2;

static TupleString2 tuple = {
    .first = "hello",
    .last = "world"
};

TupleString2 *get_headers(Request *req)
{
    return &tuple;
}
const koffi = require("koffi");
const lib = koffi.load("./138.so");

const StringTuple2 = koffi.struct({
    first: "char *",
    last: "char *"
})

const rust_get_headers = lib.func("get_headers", koffi.pointer(StringTuple2), [koffi.pointer(koffi.opaque("Request"))]);

let ret = rust_get_headers(null);
let tuple = koffi.decode(ret, StringTuple2);

console.log(tuple);

@hanako-eo
Copy link
Author

hanako-eo commented Feb 22, 2024

I tried to do this with one to but I have the same problem

@hanako-eo
Copy link
Author

I'm mainly looking to get a vector from rust

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants