如何公开C++;类,而不构建模块 我想知道是否有任何方法将C++类暴露给Python,但不需要构建中间共享库。
这是我想要的情景。例如,我有以下C++类:如何公开C++;类,而不构建模块 我想知道是否有任何方法将C++类暴露给Python,但不需要构建中间共享库。,c++,python,swig,boost-python,C++,Python,Swig,Boost Python,这是我想要的情景。例如,我有以下C++类: class toto { public: toto(int iValue1_, int iValue2_): iValue1(iValue1_), iValue2(iValue2_) {} int Addition(void) const {if (!this) return 0; return iValue1 + iValue2;} private: int iValu
class toto
{
public:
toto(int iValue1_, int iValue2_): iValue1(iValue1_), iValue2(iValue2_) {}
int Addition(void) const {if (!this) return 0; return iValue1 + iValue2;}
private:
int iValue1;
int iValue2;
};
我希望以某种方式将此类(或其intance)转换为PyObject*,以便将其作为参数(args)发送到例如PyObject_CallObject:
PyObject* PyObject_CallObject(PyObject* wrapperFunction, PyObject* args)
另一方面,在我的Python端,我将有一个RePabPrime'函数,它将指针放在C++类(或它的实例)上作为参数,调用它的方法或使用其属性:
def wrapper_function(cPlusPlusClass):
instance = cPlusPlusClass(4, 5)
result = instance.Addition()
如您所见,我并不真的需要/希望有一个单独的共享库或使用boostpython构建一个模块。我需要的是找到一种方法来将C++代码转换为PyObject并将其发送到Python。我找不到通过C python库、boost或SWIG实现这一点的方法
你知道吗?
谢谢你的帮助。据我所知,要做到这一点并不容易
用C++既不带模块也不使用中间库来扩展Python,则需要动态加载库,然后导入函数。该模块使用这种方法。要用C++实现同样的代码,需要编写一个
在Python中使用。尽管它没有提供精确的调用语法,并且引入了中间库,但它可能比构建<代码> cType < /代码>库更省力,可以直接与C++连接。
ctypes
然而,如果要引入一个中间库,那么使用Boost.Python、SWIG或其他一些C++/Python语言绑定工具可能是值得的。虽然这些工具中的许多将通过模块引入扩展,但它们通常提供更清晰的调用约定、更好的绑定过程错误检查,并且可能更易于维护。
遵循C++类(注意!默认构造函数是强制的):
可以通过以下宏通过boost暴露:BOOST_PYTHON_MODULE(ModuleTestBoost)
{
class_<TwoValues>("TwoValues")
.def("Addition", &TWOVALUES::Addition)
.add_property("Value1", &TWOVALUES::iValue1)
.add_property("Value2", &TWOVALUES::iValue2);
};
然后,在C++侧,我可以通过同时发送类的实例来调用这个函数,例如:
Py_Initialize();
try
{
TwoValues instance(5, 10);
initModuleTestBoost();
object python_script = import("python_script");
object wrapper_function = python_script.attr("wrapper_function");
wrapper_function(&instance);
}
catch (error_already_set)
{
PyErr_Print();
}
Py_Finalize();
优点:
- 我不需要构建任何共享库或二进制文件
- 当我使用Boost时,我不需要担心内存管理 &参考计数
- 我没有使用共享boost指针(boost::shared_ptr)指向 我的班级实例
def wrapper_function(instance):
result = instance.Addition()
myfile = open(r"C:\...\testboostexample.txt", "w")
output = 'First variable is {0}, second variable is {1} and finally the addition is {2}'.format(instance.Value1, instance.Value2, result)
myfile .write(output)
myfile .close()
Py_Initialize();
try
{
TwoValues instance(5, 10);
initModuleTestBoost();
object python_script = import("python_script");
object wrapper_function = python_script.attr("wrapper_function");
wrapper_function(&instance);
}
catch (error_already_set)
{
PyErr_Print();
}
Py_Finalize();