gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 04:58:07 25 4
gpt4 key购买 nike

我正在创建小型 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; }
}

我怎样才能让 python 可以执行此操作 (C++):

 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

我的代码用于调用传递给类的 ptr 的基本方法调用。这可能是基本用例,但我无法使其工作。我试过 shared_ptr 但失败了。是否应该使用 shared_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。

关于python - 如何使用 boost python 将字节数组从 C++ 发送到 python 并将其修改后返回?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19607943/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com