cmatlabshared-libraries

Strange/Odd characters appear when calling library functions in Matlab


I'm using MATLAB to call functions from an external library to control a device, the problem I have is that with specific function the arguments are not converted properly and strange characters appear in its place.

For example, calling:

    ERRCODE = calllib ('MEDAQLib','ExecSCmd',1,int8('Laser_On'));

where ExecSCmd arguments in libfunctionview are defined as ulong,int8Ptr

Now, when I log the commands this happens

ExecSCmd, Enter, instanceHandle= 1, sensorCommand= 'Laser_On'“£~ð' MESensor::SensorCommand, Enter, this= 0x30c07b50, S_Command= Laser_On'“£~ð ErrorMsg::Error_SetText set, Message: -14 (ERR_UNKNOWN_SENSOR_COMMAND): Laser_On'“£~ð

Instead of Laser_On'“£~ð it's meant to show a clean Laser_On like it does with other functions. It gets weirder, sometimes calling this will randomly work, but done so very few times.

Similar issues arise when using a different computer, with same Matlab version, same compiler, same library, but different OS. The compiler used is Windows SDK 7.1, Matlab Version 2012b.

Why do these weird characters appear in the arguments?


Solution

  • It seems the library expects the string to be zero-terminated, like a string in C. You could try int8(['Laser_On', char(0)]) instead. Indeed, the reference says that your array is passed as what C denotes by char *, a pointer to the first character 'L' of your string. Instead of using just int8, you could also write more consisely int8(char(['Laser_On', 0])).

    The strange characters appear because the logger in your library prints one character after another until it reaches a zero byte. Thus, behavior becomes undefined in your case and you have the logger print those odd characters until it hits zero by chance.