Passing structured data to native code using JS-ctypes
-
14-06-2021 - |
Question
I am developing a Firefox extension and I need to perform some high-speed calculations using structured data currently presented in the form of Javascript object. To achieve this I'm planning to write the C library to be invoked using js-ctypes. Is there any way to pass Javascript object to native library using JS-ctypes? Example of data:
{vendors:
{Oracle: {products:
{Exadata: {spec1: 111, spec2: 222}, Exalogic:
{spec1: 111, spec2: 222}}}, IBM: {products: {WebSphere: {spec1: 111, spec2:222}}}
}}
Thanks in advance.
Solution
You can only pass in types that are valid in C. And since C has no concept of dictionary types or similar you cannot pass those to your C code. So you basically have two options:
- You use
JSON.stringify()
to turn this object into a string. You then have to find some C library that can parse JSON and will allow you to work with it somehow. - You convert your JavaScript data into types that C can understand directly. For example, you could pass in an array of
Vendor
structures with eachVendor
structure containing a pointer to an array ofProduct
structures. Of course, your C code will need to know the size of the array - this will have to be a function parameter for the former array and aVendor
structure field for the latter.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow