如何将 Python 中的字节对象传递给用 Swig 包装的 C++ 函数?

How to pass bytes object in Python to a C++ function wrapped with Swig?

我在 Python 中有一个字节变量,我想将其传递给 C++ 函数,然后想 return 稍后也通过 C++ 函数传递这些字节。 C++ 代码包装在 Swig 中。有谁知道我该怎么做或有一个基本的例子吗?我试过在 C++ 中使用 void* 作为类型,但我无法让它工作。

C++ example.hpp 代码:

class MyTestClass {
public:    
    void set_data(void* data);
    void* get_data();

private:
    void* data;
};

C++ example.cpp 代码:

void MyTestClass::set_data(void* data)
{
    this->data = data;
}

void* MyTestClass::get_data()
{
    return data;
}

Swig 接口文件:

/* File : example.i */
%module example

%include <std_string.i>

%{
    #include "example.hpp"
%}

%include "example.hpp"

测试Python代码:

from example import MyTestClass

test_class = MyTestClass()

data1 = b"test"
test_class.set_data(data1)

data2 = test_class.get_data()    
print(data2)

编译:

swig -c++ -python -modern -py3 example.i
export CC=g++
python setup.py build_ext --inplace

错误:

Traceback (most recent call last):
  File "./test.py", line 6, in <module>
    test_class.set_data(data_1)
  File "example.py", line 119, in set_data
    return _example.MyTestClass_set_data(self, data)
TypeError: in method 'MyTestClass_set_data', argument 2 of type 'void *'

您应该使用 char* 而不是 void*。 此外,您不应使用

%include <std_string.i>

在 example.i 文件中,因为它具有将 char * 转换为字符串的类型映射定义。

小问题:您 example.cpp 应 #include "example.hpp" 以获得 MyTestCLass 的定义。

我设法让它与 cstring.i 模板一起工作:

%cstring_output_allocate_size(char** data_out, int* maxdata, NULL)

当我设置数据时,我也设置了大小,我用它来设置最大数据。第三个参数为NULL,不自由,因为数据仅供参考。