我有一个像这样的 C++ 类方法:
class BinaryData
{
public:
...
void serialize(unsigned char* buf) const;
};
serialize
函数只是获取二进制数据作为unsigned char*
。
我使用 SWIG 来包装这个类。
我想在 python 中将二进制数据读取为 byte array
或 int array
。
Python 代码:
buf = [1] * 1000;
binData.serialize(buf);
但出现无法转换为unsigned char*
的异常。
如何在 python 中调用此函数?
最佳答案
最简单的做法是在 Python 中转换它:
buf = [1] * 1000;
binData.serialize(''.join(buf));
开箱即用,但可能不够优雅,具体取决于 Python 用户的期望。您可以使用 SWIG 解决此问题 inside Python code ,例如与:
%feature("shadow") BinaryData::serialize(unsigned char *) %{
def serialize(*args):
#do something before
args = (args[0], ''.join(args[1]))
$action
#do something after
%}
或者在生成的接口(interface)代码中,例如使用 buffers protocol :
%typemap(in) unsigned char *buf %{
// use PyObject_CheckBuffer and
// PyObject_GetBuffer to work with the underlying buffer
// AND/OR
// use PyIter_Check and
// PyObject_GetIter
%}
根据您的首选编程语言和其他特定情况的限制,您更愿意在何处执行此操作是个人选择。
关于python - 如何使用 Swig 将 unsigned char* 转换为 Python 列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43179780/