[英]Fill char* with binary data in a c++ Python wrapped class with SWIG
我已经用swig包装了一个c ++类供python使用。 我的课是这样的:
public class DataHolder
{
public:
char* BinaryData;
long Length;
}
public class MyProcessor
{
public:
int process(DataHolder& holder)
{
holder.BinaryData = assign some binary data;
holder.Length = 1024;
}
}
我想要的是python这样的东西:
import Module
from Module import *
proc = MyProcessor();
holder = DataHolder();
proc.process(holder);
#use holder.BinaryData to, for example, print
任何帮助将不胜感激,非常感谢!
您的示例C ++代码不太合法(它看起来更像Java!),但是一旦我解决了这个问题,并为process
添加了一些实际的东西,就可以按照您的希望包装它。
与我以前的答案相比,主要的变化是长度是从类内部读取的,而不是在容器上调用方法的结果。 这有点丑陋,因为我不得不对C ++“ this”对象的名称进行硬编码, $self
引用了Python对象。 因此,我将类型图仅在确定其合法且正确的有限情况下应用。
所以我的最终接口文件最终看起来像:
%module test
%typemap(out) char *DataHolder::BinaryData {
Py_buffer *buf=(Py_buffer*)malloc(sizeof *buf);
if (PyBuffer_FillInfo(buf, NULL, $1, arg1->Length, true, PyBUF_ND)) {
// Error, handle
}
$result = PyMemoryView_FromBuffer(buf);
}
%inline %{
class DataHolder
{
public:
char* BinaryData;
long Length;
};
class MyProcessor
{
public:
int process(DataHolder& holder)
{
static char val[] = "Hello\0Binary\0World\n!";
holder.BinaryData = val;
holder.Length = sizeof val;
return 0;
}
};
%}
我测试过的:
from test import *
proc = MyProcessor()
holder = DataHolder()
proc.process(holder)
data = holder.BinaryData
print(repr(data))
print(data.tobytes())
我在这里以Python3为目标,但完全相同的代码也适用于Python 2.7。 当编译并运行时,给出了:
swig2.0 -c++ -Wall -py3 -python test.i
g++ -Wall -shared -o _test.so test_wrap.cxx -I/usr/include/python3.4
python3 run.py
<memory at 0xb7271f9c>
b'Hello\x00Binary\x00World\n!\x00'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.