I am using C++ functions in Python by SWIG,and I met a problem now.
When I pass a char * from C++ to Python, the char * is truncted by Python.
For example:
example.h:
char * fun()
{
return "abc\0de";
}
now in Python,we call
example.fun()
it only print
“abc”
instead of
“abc\0de”
the data behind ‘\0’ is deleted by Python.
I want to get all the chars(it is a binary data that can contains ‘\0’) from fun() in C++,
and any advise is appreciated
C/C++ strings are NULL-terminated which means that the first
\0character denotes the end of the string.When a function returns a pointer to such a string, the caller (SWIG in this case) has no way of knowing if there is more data after the first
\0so that’s why you only get the first part.So first thing to do is to change your C function to return not just the string but its length as well. Since there can be only one return value we’ll use pointer arguments instead.
The SWIG docs suggest using the
cstring.ilibrary to wrap such functions. In particullar, the last macro does exactly what you need.Read the docs to learn how to use it.