MATLAB: How to pass a string (LPSTR) command to the C++ function

ccalllibdllloadlibraryMATLAB

Hello all,
I have a C++-dll, which I have loaded with loadlibrary. I can also list the functions in the dll, which tells me that the call is
[int16, int8Ptr] = wsaSetSCPI(int64 (handle), int8Ptr (command))
command is basically a SCPI command string that I need to pass in and never see again. My call looks like this
command = 'INPUT:MODE SH';
[error, command] = calllib('wsaInterface', 'wsaSetSCPI', hndl, command)
It returns:
Error using calllib
Array must be numeric or logical or a pointer to one
‘ or “ does not make a difference here. I also tried converting it around a bit, but didn’t find the right way to pass it. I believe that when using the ‘ ‘ notation, it is passed as a char array, so essentially a int8 array. In the C++ dll the command parameter is defined as LPSTR.
What surprises me, is that MATLAB does not seem to mind the LPSTR, because in another function call I can pass an empty, preallocated char array by reference and get back reasonable responses written into it. If anything, I would expect problems with that.
Can you please point me in the right direction on how to pass the command on to my function?

Best Answer

There are two ways to work around this and you almost got it.
Option 1: When casting from a char to a uint8 type in matlab to pass as a string you must manualy add the NULL :
[uint8('*IDN?') 0] %concatinate a null on onto end of string
Option two: Fix the function decleration so that MATLAB will accept a character array as input. There are two ways to do this: You can create a modified header file using char * or other type that matlab will translate to a cstring or you can create a loader file with the mfilename option to loadlibrary and manualy modify that as needed.
For a quick fix I recommend option 1. If you want to simplify the process and make other fixes I suggest a custom loader file.
Related Question