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

Node.js ffi-napi: How to handle unknown length strings in callback functions? #645

Open
yewanji opened this issue Feb 4, 2024 · 0 comments

Comments

@yewanji
Copy link

yewanji commented Feb 4, 2024

Issue Description:
I'm facing an issue with ffi-napi when working with callback functions that return strings of unknown lengths from a C++ library. The problem is that I need to set csStringPointer.size to a specific value before calling the C++ function, but I don't know the exact length of the returned string in advance. Setting it too large could lead to memory waste, while setting it too small may result in string truncation.

Code Snippet:

javascript
Copy code
const cString = ref.types.CString;
const csStringPointer = ref.refType(cString);
csStringPointer.size = 500;

const CallbackFunc = ffi.Function(ref.types.void, ['bool', csStringPointer]);

const dllLib = ffi.Library(dllPath, {
'pollWpsResult': ['void', [CallbackFunc]]
});

dllLib.pollWpsResult(function (status, strPtr) {
// Issue: Unable to determine the correct size for csStringPointer.
// The length of the returned string is unknown.
const value = iconv.decode(strPtr, 'gbk');
console.log('Status:', status, 'Message:', value);
});
Expected Behavior:
I would like to find a solution or best practice for handling strings of unknown lengths when using ffi-napi. Ideally, there should be a way to dynamically allocate memory for the string in the callback without predefining the size.

Additional Information:

Operating System: [Your OS]
Node.js Version: v12.14.1
ffi-napi Version: ^2.4.5
Feel free to customize the issue template with more details specific to your project. I hope this helps, and let me know if you need further assistance.

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

1 participant