boost::python sharing native c++ object with python
Joerg Sauer
NeXTStep at programmatic.de
Fri Aug 24 13:38:00 EDT 2001
Hi,
hopefully the subject is attracting!?
I know how to create an extension module using boost and how to make a
class wrapper using python::class_builder. That works fine!
Now that I have an extension DLL I want to embed python in my
application.
How can I create an c++ class object in the c++ app and export this
object to the python instance (not as function parameter but as object
at global or module level)?
Suggest I have
---myclass.h-------------
class DLLAPI myclass
{
public:
myclass(){}
void setval(int x){_x=x;}
int getval(){return _x;}
private:
int _x;
};
---myboostmod.h------------
#include "myclass.h"
BOOST_PYTHON_MODULE_INIT(mymod)
{
python::module_builder this_module("mymod");
// Create the Python type object for our extension class.
python::class_builder<myclass> myclass_class(this_module,
"myclass");
myclass_class.def(python::constructor<int>());
myclass_class.def(&myclass::setval, "setval");
myclass_class.def(&myclass::getval, "getval");
}
now I have a main programm
----------main.cpp-----------
#include <iostreams>
#include <Python.h>
#include "myboostmod.h" //???? or just #include "myclass.h"
using std::cout;
int main(int argc, char** argv)
{
PyObject *pMod, *pDict, *pObject;
Py_Initialize();
pMod = PyImport_ImportModule("mymod");
// Now that I have python up and ready, I want to export a c++
// class
myclass mc1;
mc1.setval(5);
// I would like to export this object with the python name mc1
// too
-->>> export mc1 to python with name mc1.
// Now I want to run a simple python statement
PyRun_SimpleString("print mc1.getval()");
PyRun_SimpleString("print mc1.setval(12345)");
// here the object should keep the value set in python
cout << "Now mc1 is:" << mc1.getval() << "\n";
Py_Exit(0);
};
Does anybody has a sollution or some hints?
Thanks in advance
Joerg
More information about the Python-list
mailing list