如何使用boost python将一个字节数组从C++发送到Python并返回修改后的数组?

3
我正在创建一个小型GUI系统,希望使用Python、Cairo和Pystacia库进行渲染。为了实现C++/Python交互,我正在使用Boost Python,但是我在指针方面遇到了一些问题。
我看到过一些类似的问题,但不太明白如何解决。
如果我有一个只有图像数据指针的结构/类:
struct ImageData{
    unsigned char* data;
    void setData(unsigned char* data) { this->data = data; } // lets assume there is more code here that manages memory
    unsigned char* getData() { return data; }
}

如何使此代码(C++)在Python中可用:

 ImageData myimage;
 myimage.data = some_image_data;
 global["myimage"] = python::ptr(&myimage);

在Python中:

 import mymodule
 from mymodule import ImageData
 myimagedata = myimage.GetData()
 #manipulate with image data and those manipulations can be read from C++ data pointer that is passed

我的代码可以调用传递给类的指针的基本方法。这可能是基本用例,但我还没有能够使其正常工作。我尝试了shared_ptr,但失败了。应该使用shared_ptr、代理类或其他方式解决吗?

1个回答

0
你在这里有一个问题,与变量的局部性有关:当你超出其作用域时,myimage 将被删除。要解决这个问题,你可以使用动态内存分配来创建它,并将指针移动到 python。
ImageData * myimage = new ImageData();
myimage->data = new ImageRawData(some_image_data); // assuming copy of the buffer
global["myimage"] = boost::python::ptr(myimage);

请注意,这段代码并没有处理Python的内存管理。你应该使用boost::python::handle<>来正确地声明你正在将内存管理转移到Python中。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接