[SOLVED] Why is 'size_t' in external C library interpreted wrong?

5 views (last 30 days)
I'm running into odd behavior while interfacing with an external C library. For a function like the following,
int foo(size_t sz, uint8_t buf[8])
{
memset(buf, 0, 8);
memcpy(buf, &sz, sizeof(size_t));
return sizeof(size_t);
}
I get the error "Warning: The data type 'error' used by function foo does not exist" when loading the library. And, when I run foo, the contents of buf don't make sense to me. If I change the size_t to uint64_t (or any other suitable integral type), then I get what I expect out in buf.
How is Matlab treating size_t? Why does it appear to be treating it as an 'error' type?
SOLUTION: Added appropriate include (stddef.h) in library header.

Answers (1)

James Tursa
James Tursa on 22 May 2020
Edited: James Tursa on 22 May 2020
I am unaware of MATLAB treating size_t differently, but there is a potential error in your code snippet:
int foo(size_t sz, uint8_t buf[8])
:
return sizeof(size_t);
The sizeof( ) operator returns a size_t type, but your function returns an int. So on a 64-bit system these will probably not match since size_t is likely a 64-bit integer and int is likely a 32-bit integer. You should change the signature to:
size_t foo(size_t sz, uint8_t buf[8])
What version of MATLAB are you running? 64-bit? Are you using the loadlibrary function? Are you loading a third party library or a library you wrote? Is there a reference to 'error' in the header that you are using? Maybe a typedef?
As for your problem, I don't see a reference to an 'error' data type in your code, so there is nothing for us to analyze.
  3 Comments
James Tursa
James Tursa on 26 May 2020
Edited: James Tursa on 26 May 2020
I am not sure what is going on yet. Can you double check to see that you have all necessary prototypes in your header file? E.g., if you are using memset( ) and memcpy( ) then you should have
#include <string.h>
in your header file to make sure the prototypes are present. This also defined size_t.
Can you post a small example complete library source code that reproduces the problem?
Tyson Lawrence
Tyson Lawrence on 26 Jun 2020
Edited: Tyson Lawrence on 26 Jun 2020
This is an insanely slow response... I got pulled away from this work for a stretch. I want to add the answer in case others have similar issues.
I resolved the problem by adding the appropriate includes in my library interface (stddef.h in this case). The problem didn't show up in my unit tests or Python API testing, so I missed it. Usually Matlab warns when something is missing.

Sign in to comment.

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!