Python 如何通过 SWIG 从 C++ 获取二进制数据(char*)?

2022-01-12 00:00:00 python char swig c++

我在 SWIG 的 Python 中使用 C++ 函数,现在遇到了一个问题.当我将 char * 从 C++ 传递给 Python 时,char * 会被 Python 截断.

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.

例如:

example.h:

char * fun()
{
    return "abcde";
}

现在在 Python 中,我们调用例子.fun()它只打印ABC"代替"abcde"'' 后面的数据被 Python 删除了.

now in Python,we call example.fun() it only print "abc" instead of "abcde" the data behind '' is deleted by Python.

我想从 C++ 中的 fun() 中获取所有字符(它是可以包含 '' 的二进制数据),并感谢任何建议

I want to get all the chars(it is a binary data that can contains '') from fun() in C++, and any advise is appreciated

推荐答案

C/C++ 字符串以 NULL 结尾,这意味着第一个 字符表示字符串的结尾.

C/C++ strings are NULL-terminated which means that the first character denotes the end of the string.

当函数返回指向此类字符串的指针时,调用者(在本例中为 SWIG)无法知道在第一个 之后是否还有更多数据,这就是为什么你只能得到第一部分.

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 so that's why you only get the first part.

所以首先要做的就是改变你的 C 函数,让它不仅返回字符串,还返回它的长度.由于只能有一个返回值,我们将使用指针参数.

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 = "abcde";
    *sz = 6;
}

SWIG 文档建议使用 cstring.i library 来包装这些函数.特别是,最后一个宏完全符合您的需要.

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.

相关文章