MATLAB: Passing a pointer from Matlab to C

libpointer

I am attempting to pass a matrix from a class in Matlab to a code in C. The code in C cannot be changed and requires a double* to be passed in as an argument. I am trying to use libpointer(…) to modify the matrix into something that can be passed to the C code through a calllib(…) function.
I cannot post all of the code because it is quite extensive. The function of the Matlab code reads:
function obj = set.RP(obj, vals)
rho = vals{1};
pres = vals{2};
if strcmp(rho,'None')
rho = obj.R;
end
if strcmp(pres, 'None')
pres = obj.P;
end
disp(rho)
disp(pres)
idxptr = libpointer('doublePtr',[rho, pres]);
disp(idxptr)
calllib('canteraLib', 'thermo_set_RP', obj.thermo, idxptr)
end
The function in the C code reads:
int thermo_set_RP(int n, double* vals)
{
try{
ThermoCabinet::item(n).setState_RP(vals[0], vals[1]);
return 0;
} catch (...) {
return handleAllExceptions(-1, ERR);
}
}
Thank you for your time
-Emil

Best Answer

Once again, it's C++ code, not C code. The code you've shown would not compile through a C compiler.
You don't need to use libpointer to pass a pointer to double to the dll. If you've given the correct header file to loadlibrary, matlab already knows to pass a pointer. There is nothing special you need to do:
assert(strcmp(class([rho, pres]), 'double')));
calllib('canteraLib', 'thermo_set_RP', obj.thermo, [rho, pres])
is all that is needed (assuming both rho and pres are double)
How do you infer that the pointer is not passed correctly if all you know is that handleAllExceptions gets triggered? If the dll had received an invalid pointer, it is more likely that you'd get an access violation error which would terminate matlab (i.e. you'd get a crash). The try ... catch statement would not detect invalid pointers, therefore it's much more likely that the values you're passing are not correct.
The best way for you to find what is going on is to attach a debugger to matlab, set a breakpoint to that function in the dll and step through the code as it is executed. Then see what happens with
ThermoCabinet::item(n).setState_RP
which is the line causing the error