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

标签 python c++ c swig

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

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 中调用此函数?

最佳答案

最简单的做法是在 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/

相关文章:

c++ - 如何使应用程序符号对库可见?

python - 如何以可读的形式打印此列表?

python - Pandas 数据框按多行分组

python - 查找树的高度,其中输入树可以有任意数量的子树

c++ - 没有错误,但没有输出

c++ - const int 变量和数字的不同类型推导

c - include_HEADERS 且没有 'all-am' 所需的目标规则

python - 带有 scrapy 的警告 "_mysql was already imported"

c++ - 与非主线程的 GUI 线程通信

c - 如何在 gcc asm 中添加一个计数器?