We've got currently an old c++ library which we want to call from node using ffi for compatibility reasons. One of the methods inside the lib has the following definition:
int CalculateValue(std::vector<DataItem> dataItems, int mode)
DataItem is defined as:
struct DataItem
{
const void *Data;
int Size;
}
I've tried some variants with ref-Array (which is apparently not the right tool to use)
const InputDataStruct = StructType({
Data: ref.refType(ref.types.void),
Size: ref.types.int32
});
const InputVectorType = ArrayType(InputDataStruct);
const calculator = ffi.Library(libPath, {
'CalculateValue': [ref.types.int32, [InputVectorType, ref.types.int32]]
});
But i keep getting segmentation faults when calling this method. I've changed the signature both on node and c++ to a single DataItem instead of vector, then it works flawlessly. How can i marshal a vector of the given structs correctly?
You can't. std::vector
is implementation defined and it's internals depend on the compiler. As of yet and as far as I know node-ffi doesn't have a type that corresponds to std::vector
.
Since it sounds like you are able to change the method signature, I'd recommend changing the method to accept a simple C style array, which is compatible with node-ffi's ArrayType
:
int CalculateValue(DataItem *dataItemsRawArray, int dataItemsCount, int mode)
{
std::vector<DataItem> dataItems{dataItemsRawArray, dataItemsRawArray + dataItemsCount};
...