Working with cstring datatypes in library function calls
Shawn Mason asked
on 6 Jan 2012
Latest activity:
Answer by Philip Borghesani
on 6 Jan 2012
I'm trying to utilize a Silicon Labs CP2112 with Matlab using the provided shared library. My question is in regards to functions with "cstring" datatypes. The referenced function is below: [int32, cstring] HidSmbus_GetString(ulong, uint16, uint16, cstring, ulong) The "cstring" argument is a char pointer to the return string for the function. It is defined in the documentation as: "deviceString is a variable of type HID_SMBUS_DEVICE_STR, which will contain a nullterminated ASCII device string on return. The string is 260 bytes on Windows and 512 bytes on Mac OS X." My problems is that the function apperas to run correctly but the value is never updated. What is the proper way to handle "cstring" types used to return data via a pointer? %% Load DLL (need to also load in the header file) clear variables; clc; [~, ~] = loadlibrary('SLABHIDtoSMBus.DLL', 'SLABCP2112.H', 'alias', 'CP2112');
libfunctions CP2112 -full %% Intialize Variables and Connect to Device.
device = libpointer('voidPtr');
deviceVid = libpointer('uint16Ptr', uint16(0));
devicePid = libpointer('uint16Ptr', uint16(0));
deviceReleaseNumber = libpointer('uint16Ptr', uint16(0));
numDevices = libpointer('ulongPtr', uint32(0));
deviceVidString = libpointer('cstring', repmat('0',260,1));
deviceNum = uint32(0);
vid = uint16(0);
pid = uint16(0);
vidOption = uint32(1);
% deviceVidString = repmat('1',1,260);%char(uint8(ones(1,260)));
[status] = calllib('CP2112', 'HidSmbus_GetNumDevices', numDevices, vid, pid);
if numDevices.Value > 0 for i = 0:(numDevices.Value - 1) [status] = calllib('CP2112', 'HidSmbus_GetString', uint32(i), vid, pid, deviceVidString, vidOption);end end unloadlibrary('CP2112');
Products |
|---|
Try using return values from your callib calls and let MATLAB do more of the work there is no need to do most of the data type conversions yourself. I am not positive this is correct (you did not give the prototype for HidSmbus_GetNumDevices) but you should be able to get the idea:
[status,numDevices,vid,pid] = calllib('CP2112', 'HidSmbus_GetNumDevices', 0, 0, 0);
strings=cell(1,numDevices);
if numDevices > 0
for i = 0:(numDevices - 1)
[status, strings{i+1}] = calllib('CP2112', 'HidSmbus_GetString', i, vid, pid, blanks(260), 1);
end
end
Philip,
Thanks for the answer. You are correct, it was as simple as reading the matlab return. I was thinking of it in terms of a normal pointer. Thanks also for the data types advice, it is much simpler now letting MATLAB take care of it.
Shawn
Contact us at files@mathworks.com
0 comments