SWIG Python 和 C++ std::string 空终止问题
我有一个基于 SWIG 的 C++ 接口,可以从 Python 调用。其中有一个函数,有一个 std::string 参数。它看起来像这样:
WrapperGet(const std::string& key);
如果使用包含 NUL 字符(例如二进制数据)的字符串参数从 Python 调用它,则 std::string 在 NUL 字符处被截断,这就是我的问题,因为它使得无法处理二进制数据。
有趣的是,其他方式可以完美地工作:
std::string WrapperResult();
这里返回的字符串可以包含不被截断的二进制数据。有人知道必须做什么吗?
更新:我调试了 SWIG 生成的代码,结果发现错误出在 C++ 大小的包装器代码中:它使用 std::string 的 c_str() 成员函数来获取字符串值。
感谢大家的想法和时间!
Possible Duplicate:
How Python can get binary data(char*) from C++ by SWIG?
I have a SWIG based C++ interface that can called from Python. There is a function in it, that has one std::string argument. It looks like this:
WrapperGet(const std::string& key);
If it is called from Python with a string argument that contains NUL character (e.g. binary data), then the std::string is truncated at the NUL character, and that is my problem, because it makes impossible to handle binary data.
What makes it interesting is that other way works perfectly:
std::string WrapperResult();
The string returned here can contain binary data without truncation. Has anybody any idea what has to be done?
UPDATE: I debugged the SWIG generated code and it turned out that the error was in the wrapper code on the C++ size: it used the c_str() member function of the std::string to get the string value.
Thanks for everybody's ideas and time!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我过去不得不处理这个问题,我只是从 SWIG 获取了
std::string
转换模板,并对其进行了一些定制,以便在创建时使用PyString_FromStringAndSize
来自std::string
的 Python 字符串和std::string
构造函数(在采用其他方式时接受大小参数)。不过,那是在 SWIG 的旧版本中 - 我认为新版本中的内置转换模板已更新为自动执行此操作。问题有可能是在C++方面吗? (例如,如 Mark Tolonen 的示例所示,其中第一个示例由于构造函数调用中嵌入的 NULL 且没有大小参数而被截断)。
I've had to deal with this in the past, and I just grabbed the
std::string
conversion template from SWIG and tailored it a bit to usePyString_FromStringAndSize
when creating a Python string from astd::string
and thestd::string
constructor that accepts a size argument when going the other way.That was with a really old version of SWIG, though - I thought the builtin conversion template in newer versions had been updated to do that automatically. Is it possible the problem is on the C++ side? (e.g. as in Mark Tolonen's examples, where the first example is truncated due to the embedded NULL in the constructor call without a size argument).
这可能就是字符串的构造方式。考虑:
从 Python 调用这些:
std::string(const char*)
的构造函数在 NULL 处停止,但显然 SWIG 可以传入并返回其中包含 NULL 的字符串。It is probably how the strings are constructed. Consider:
Calling these from Python:
The constructor for
std::string(const char*)
stops at the NULL, but clearly SWIG can pass in and return strings with a NULL in them.