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).