SWIG 'cstring.i' Python 返回字节类型而不是字符串类型 [英] SWIG 'cstring.i' Python return byte type instead of string type
问题描述
我有一个 C 函数,比如
I have a C function like
int foo(void ** buf, int * buf_size)
并且我使用 cstring.i
将它包装起来以便在 Python 3 中使用.包装后的 Python 函数的结果是字符串类型.
And I use cstring.i
to wrap it for use in Python 3. The result of the wrapped Python function is of type string.
有没有办法得到二进制类型的结果?
Is there a way to get the result as type binary?
背景:buf
填充的数据是 msgpack 编码的数据,因此在 Python 中使用 str.decode
不是一种选择.Python 的 msgpack 实现只接受二进制数据.
Background: The data buf
gets filled with is msgpack encoded data, so using str.decode
in Python is not an option. The msgpack implementations for Python only accept binary data.
推荐答案
如果你使用 %cstring_output_allocate_size
包装函数 _wrap_foo
调用 SWIG_FromCharPtrAndSize()
具有以下解码逻辑:
If you use %cstring_output_allocate_size
the wrapper function _wrap_foo
calls SWIG_FromCharPtrAndSize()
which has the following decoding logic:
#if PY_VERSION_HEX >= 0x03000000
#if defined(SWIG_PYTHON_STRICT_BYTE_CHAR)
return PyBytes_FromStringAndSize(carray, (Py_ssize_t)(size));
#else
#if PY_VERSION_HEX >= 0x03010000
return PyUnicode_DecodeUTF8(carray, (Py_ssize_t)(size), "surrogateescape");
#else
return PyUnicode_FromStringAndSize(carray, (Py_ssize_t)(size));
#endif
#endif
#else
return PyString_FromStringAndSize(carray, (Py_ssize_t)(size));
#endif
因此您可以通过#defining SWIG_PYTHON_STRICT_BYTE_CHAR
获取字节而不是 unicode 字符串.这记录在 http://www.swig.org/Doc3.0/Python.html 所以这是一个官方功能.但由于它是一个全局开关,因此只有在您希望所有字符串参数都映射到字节时才有用.如果您需要在 API 中混合使用 str
和 bytes
,我能看到的唯一解决方案是自定义类型映射.
So you can get bytes instead of unicode string by #defining SWIG_PYTHON_STRICT_BYTE_CHAR
. This is documented in http://www.swig.org/Doc3.0/Python.html so it's an official feature. But since it's a global switch, it's only useful if you want all string parameters to be mapped to bytes. If you need a mix of str
and bytes
in your API the only solution I can see is a custom typemap.
这篇关于SWIG 'cstring.i' Python 返回字节类型而不是字符串类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!