2017-04-03 292 views
0

我有一个C++类的方法是这样的:如何使用Swig将unsigned char *转换为Python列表?

class BinaryData 
{ 
public: 
    ... 
    void serialize(unsigned char* buf) const; 
}; 

serialize功能只得到二进制数据unsigned char*。 我使用SWIG来包装这个类。 我想在python中读取二进制数据byte arrayint array

Python代码:

buf = [1] * 1000; 
binData.serialize(buf); 

但它出现异常,不能转换为unsigned char*。 如何在python中调用这个函数?

回答

1

最简单的事情做的是将其转换内部的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 
%} 

或者在生成的接口代码中,例如,使用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 
%} 

在那里你喜欢做,这是根据您的首选编程语言和其他情况具体限制个人的选择。

相关问题