有人能建议一种在什么时候用Cython操作c++对象的方法吗 一个类的c++实例应该提供给另一个封装的构造函数 类别如下所述?在
请查看pyx文件中关于类PySession的注释,它 接受python PyConfigParams对象作为参数,然后需要 从中提取值以构造c++ConfigParams 对象。然后使用ConfigParams对象向构造函数提供数据 会议记录。在
最好有一个能让我“注射”的程序 PyConfigParams对象包装的ConfigParams c++对象 直接进入Session的构造函数,而不必拆卸 它首先构建一个新的c++对象来提供给构造函数。 这当然管用。然而,实现这个解决方案是一种麻烦的、有点残酷的方法,更不用说不可靠了。在
我知道PyCapsule,但是它可能需要接触c++头,这是我不能做的。在
与此相关,但另一个问题是:如果我需要包装呢 类(我们假设这里是PyScript)来模拟C++的行为 通过返回ConfigParams实例实现的api?我需要做 反转并拆除c++对象以构建Python PyConfigParams 然后返回给Python世界中的Python用户? 欢迎提出任何建议! 谢谢您!在
假设我有两个名为ConfigParams和Session的c++类。 ConfigParams的实例用于向 会话类:
// ConfigParams.h
#include <iostream>
using namespace std;
class ConfigParams
{
int parameter1;
public:
ConfigParams(int par1) { this->parameter1 = par1;}
int getPar1() { return this->parameter1; }
};
# configparams.pxd
cdef extern from "configparams.h":
cppclass ConfigParams:
ConfigParams(int par1)
int getPar1()
# configparams.pyx
cdef class PyConfigParams:
cdef ConfigParams* thisptr
def __cinit__(self, i):
self.thisptr = new ConfigParams(<int> i)
def getPar1(self):
return self.thisptr.getPar1()
# session.pxd
from configparams cimport *
cdef extern from "session.h":
cdef cppclass Session:
Session(ConfigParams parameters)
void doSomething()
# session.pyx
cdef class PySession:
cdef Session* thisptr
def __cinit__(self, pars):
# Note that here I have to extract the values
# from the pars (python PyConfigParams object)
# in order to build a c++ ConfigParams object
# which feeds the c ++ constructor of Session.
cdef ConfigParams* cpppargsptr = new ConfigParams(<int> pars.getPar1())
self.thisptr = new Session(cpppargsptr[0])
def doSomething(self):
self.thisptr.doSomething()
解决方案:
在中转发声明PyConfigParams配置参数.pxd模块(因此可以从会话.pyx模块)
在中导入PyConfigParams会话.pyx模块,并为constructor转换参数,这将授予对指向c++对象的PyConfigParams指针的访问权,这将需要取消对该对象的引用。在
^{pr2}$相关问题 更多 >
编程相关推荐