如何使用 Swig 将 unsigned char* 转换为 Python 列表?

How to convert unsigned char* to Python list using Swig?

我有一个像这样的 C++ class 方法:

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

serialize 函数只是获取二进制数据作为 unsigned char*。 我使用 SWIG 包装这个 class。 我想将二进制数据读取为 byte arrayint array in python.

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
%}

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

根据您的首选编程语言和其他特定情况的限制,您更喜欢在何处执行此操作是个人选择。