How Python can get binary data(char*) from C++ by SWIG?

后端 未结 3 812
忘掉有多难
忘掉有多难 2020-12-21 04:38

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:

e

3条回答
  •  时光取名叫无心
    2020-12-21 05:04

    C/C++ strings are NULL-terminated which means that the first \0 character 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 \0 so 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.

    void fun(char** s, int *sz)
    {
        *s = "abc\0de";
        *sz = 6;
    }
    

    The SWIG docs suggest using the cstring.i library to wrap such functions. In particullar, the last macro does exactly what you need.

    %cstring_output_allocate_size(parm, szparm, release)
    

    Read the docs to learn how to use it.

提交回复
热议问题