I am trying to build a DLL in C++ and call it from MATLAB by using loadlibrary
and calllib
instructions. It works for one value and it return a value normally, but now I am trying to return a whole array from C++ DLL to MATLAB as an output of a function.
As you know C++ usually return the arrays as pointers but this don't work with MATLAB ... I searched for that at the internet and they are using some MEX function but it is not clear ...
Can you explain how to return an array from C++ DLL to MATLAB calllib
and how should we return it from C++ code ?
Consider a DLL that exposes the following C function:
void getData(double *x, const int len)
{
for(int i=0; i<len; i++) {
x[i] = i;
}
}
It takes an array already allocated an its length, and fills it with incremental values.
In MATLAB, first we load the library:
>> loadlibrary('mydll.dll', 'mydll.h')
>> libfunctions mydll -full
Functions in library mydll:
doublePtr getData(doublePtr, int32)
To call the exposed function, we use libpointer
:
>> p = libpointer('doublePtr', zeros(1,10)) % initialize array of 10 elements
p =
libpointer
>> get(p)
Value: [0 0 0 0 0 0 0 0 0 0]
DataType: 'doublePtr'
>> calllib('mydll', 'getData', p, 10) % call C function
>> get(p)
Value: [0 1 2 3 4 5 6 7 8 9]
DataType: 'doublePtr'
we could also simply pass regular vectors and MATLAB will take care of marshalling:
>> x = calllib('mydll', 'getData', zeros(1,10), 10)
x =
0 1 2 3 4 5 6 7 8 9
note that in this case, the modified array will be returned as an output (since builtin types will not be modified in-place).
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments