如何从C++;使用boostpython创建python并返回修改后的python?
我正在创建小型GUI系统,我想使用python、cairo和Pystasia库进行渲染。对于C++/Python交互,我使用boostpython,但指针有问题 我见过这种问题被问过几次,但不太明白如何解决它 如果我有一个struct/class,其中只有图像数据指针:如何从C++;使用boostpython创建python并返回修改后的python?,python,boost-python,cairo,Python,Boost Python,Cairo,我正在创建小型GUI系统,我想使用python、cairo和Pystasia库进行渲染。对于C++/Python交互,我使用boostpython,但指针有问题 我见过这种问题被问过几次,但不太明白如何解决它 如果我有一个struct/class,其中只有图像数据指针: struct ImageData{ unsigned char* data; void setData(unsigned char* data) { this->data = data; } // lets
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; }
}
我如何使python可以使用它来执行此操作(C++):
在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
我的代码用于调用传递给类的ptr的基本方法调用。这可能是基本的用例,但我还没能让它工作。我尝试了共享\u ptr,但失败了。是否应该使用共享ptr、代理类或其他方式解决此问题?您的变量的位置有问题:当您超出其范围时,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
ImageData * myimage = new ImageData();
myimage->data = new ImageRawData(some_image_data); // assuming copy of the buffer
global["myimage"] = boost::python::ptr(myimage);