我是新手来提升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)