我是新手来提升python.我必须首先在cpp代码中初始化一个cpp类实例,然后将这个cpp实例传递给python代码,使用python类实例来调用它(cpp实例).我已经尝试过Python/C API方法但是失败了,所以我想知道如何将c ++类实例传递给python类.
以下是我的代码,改进了boost python演示.
在main.cpp中
#include <python2.6/Python.h>
#include <boost/python.hpp>
#include <iostream>
using namespace boost::python;
using namespace std;
class World
{
private:
string name;
public:
void set(string name)
{
this->name = name;
}
void greet()
{
cout << "hello, I am " << name << endl;
}
};
typedef boost::shared_ptr< World > world_ptr;
BOOST_PYTHON_MODULE(hello)
{
class_<World>("World")
.def("greet", &World::greet)
.def("set", &World::set)
;
register_ptr_to_python<world_ptr>();
};
int main()
{
Py_Initialize();
PyRun_SimpleString("import sys");
PyRun_SimpleString("sys.path.append('./')");
world_ptr worldObjectPtr (new World);
worldObjectPtr->set("C++!");
try
{
inithello();
PyObject* pModule …Run Code Online (Sandbox Code Playgroud) 我想知道是否有任何方法可以将C++类暴露给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 iValue1;
int iValue2;
};
Run Code Online (Sandbox Code Playgroud)
我想以某种方式将此类(或其intance)转换为PyObject*,以便将其作为paremter(args)发送到例如PyObject_CallObject:
PyObject* PyObject_CallObject(PyObject* wrapperFunction, PyObject* args)
Run Code Online (Sandbox Code Playgroud)
另一方面,在我的python方面,我将有一个wrapperFunction,它将我的C++类(或其实例)上的指针作为参数获取,并调用其方法或使用其属性:
def wrapper_function(cPlusPlusClass):
instance = cPlusPlusClass(4, 5)
result = instance.Addition()
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,我并不需要/希望拥有单独的共享库或通过boost python构建模块.我需要的只是找到一种方法将C++代码转换为PyObject并将其发送到python.我无法通过C python库,boost或SWIG找到一种方法.
你有什么主意吗?谢谢你的帮助.
我需要使用Python C API将C++类公开到嵌入式python中.
换句话说,就像这样: 将C++类实例暴露给python嵌入式解释器, 但根本不使用Boost.
我想把它放在这个应用程序是相当老的,编译器,环境等......无法处理Boost.