Mqx
Mqxβ€’2w ago

FFI callback with multiple parameters

Hey could someone please help me with this interface definition:
MODULE_API auto getDevices(
void (*callback_fn)(
const char *name,
const char *path,
const char *manufacturer,
const char *serial_number
),
ErrorCallbackT error_callback = nullptr
) -> int;
const getDevices : Deno.ForeignFunction = {
parameters: [
'function',
'function'
],
result: 'i32',
nonblocking: true
}
MODULE_API auto getDevices(
void (*callback_fn)(
const char *name,
const char *path,
const char *manufacturer,
const char *serial_number
),
ErrorCallbackT error_callback = nullptr
) -> int;
const getDevices : Deno.ForeignFunction = {
parameters: [
'function',
'function'
],
result: 'i32',
nonblocking: true
}
const {symbols} = Deno.dlopen('', {
getDevices
})

await symbols.getDevices(
(
name,
path,
manufacturer,
serial_number
) => {
devices.push({
name,
path,
manufacturer,
serial_number
});
},
(error) => {console.log(error);}
)

console.log(devices);
const {symbols} = Deno.dlopen('', {
getDevices
})

await symbols.getDevices(
(
name,
path,
manufacturer,
serial_number
) => {
devices.push({
name,
path,
manufacturer,
serial_number
});
},
(error) => {console.log(error);}
)

console.log(devices);
I would like to know on how to properly define my FFI interface for that kind of C++ function. I want to understand how this works correctly, because I think my current approach is completely wrong πŸ˜… I want to transmit kind of an β€žobjectβ€œ from C++ to TypeScript. And I read somewhere that this is the preferred method, using a callback function. Thanks 😊
9 Replies
AapoAlas
AapoAlasβ€’2w ago
Right, you'll need to use the Deno.UnsafeCallback API to create the callbacks
Mqx
MqxOPβ€’2w ago
πŸ‘πŸ» will try. Thanks
AapoAlas
AapoAlasβ€’2w ago
Did you succeed? πŸ™‚
Mqx
MqxOPβ€’2w ago
I think so, yes. I currently don’t have a dll on my hand to test it πŸ˜… but I think this should work: https://github.com/Serial-IO/serial/blob/main/src/ffi/get_devices.ts it still needs to refined, cleared up und refactored but I think this should work
GitHub
serial/src/ffi/get_devices.ts at main Β· Serial-IO/serial
Core library for the serial communication. Contribute to Serial-IO/serial development by creating an account on GitHub.
Mqx
MqxOPβ€’2w ago
AapoAlas
AapoAlasβ€’2w ago
No idea unfortunately. I haven't really played around with JSR. You might be able to test with eg. a raw GitHub URL without publishing to JSR though.
Mqx
MqxOPβ€’2w ago
Okay. Problem is Deno.dlopen() supports a local path as a string or an URL object. Question is if the URL object needs to be an actual URL like https:// or if it also supports file:// URLs And if Deno is able to resolve these When installed as a JSR package
AapoAlas
AapoAlasβ€’2w ago
No idea.
Mqx
MqxOPβ€’2w ago
I will test that

Did you find this page helpful?