MATLAB: Issue with calling function from a DLL with calllib

ccalllibdll

Dear all, I am havind difficulties to call a function of a shared library. This function is defined in the C header like:
ssize_t myfun (const int id, void * buffer, size_t buffer_size_bytes, unsigned timeout)
First of all I am a bit confused because when I call "libfunctionsview" the argument "buffer_size_bytes" is listed as a voidPtr, but I was expecting an integer. However, I am unsure about the equivalence between size_t and Matlab types.
I have sample code in C:
unsigned long long buffer[1024];
ret = sc_tdc_pipe_read2(id, (void *)buffer, 1024*8, 50);
Whatever I am writing in Matlab, and honestly I started to write random code, is crashing Matlab.
I've tried:
[ret pp]= calllib('mylib','myfun',id,p,1024*8, 50)
or
[ret pp]= calllib('mylib','myfun',id,p,p2, 50)
with
pp = libpointer('voidPtr'); or
pp = libpointer('uint64Ptr'); or
pp = libpointer('voidPtr',uint64(zeros([1024 1]))); or
pp = libpointer('voidPtr',uint64(zeros([1 1024]))); or
pp = libpointer('voidPtr'); setdatatype(pp,'uint64',zeros([1024 1])); or
pp = libpointer('uint64Ptr');
and p2 = libpointer('voidPtr',1024*8);
Nothing worked. I am speaking with who wrote the DLL, but they are not experts in Matlab and I am no expert in C. Anyone that has experience with calllibe and somehow have any advice?
Kind regards,
Alessandro

Best Answer

You need to fix the input type of buffer_size_bytes first. Loadlibrary requires a header file that compiles stand alone. Your example program must have one or more #include statements before the one that defines sc_tdc_pipe_read2. There are two ways to fix this
  1. Modify the existing header or create a new one that has the needed includes
  2. Or create a prototype file with the mfilename option to loadlibrary and fix the rhs argument types for the function. With 32 bit code size_t should be uint32 and it should be uint64 for 64 bit code.
When the library is correctly loaded ether of these code blocks should work:
[ret,buffer]=calllib(mylib,myfun,uint64(zeros(1024,1),1024*8,50)
or
pp=libpointer('uint64Ptr',zeros([1024 1]))
ret=calllib(mylib,myfun,pp,1024*8,50)
buffer=pp.value;
Some of your other examples should work too but these are the preferable ones.
Related Question