[C++-sig] Calling member function of object created in C++ via embedded Python
Ron Brown, Jr.
rbrown at gamry.com
Thu Apr 12 23:01:01 CEST 2007
Please forgive me if this is a ridiculously simple question, but I'm new
to both Python and Boost.Python, and I'm having hard time getting my
bearings.
Essentially, I have a C++ application with Python embedded via
Boost.Python. I have a class which I instantiate on the C++ side. This
class is also exposed to Python via a BOOST_PYTHON_MODULE.
Now normally (at least according to any examples I've found), you would
expose that class to Python, and instantiate that class on the Python
side. But as this is an embedded Python application, I'd like to
instantiate the object on the C++ side, and somehow be able to call that
object's member functions from Python.
Is this possible, and if so, how would one go about doing it?
I'll try and explain using a modified version of the example from
http://www.boost.org/libs/python/doc/tutorial/doc/html/python/exposing.html
Thanks!
-Ron
----------------------------------------
#include <boost/python.hpp>
using namespace boost::python;
class World
{
public:
void set(std::string msg) { this->msg = msg; }
std::string greet() { return msg; }
std::string msg;
};
BOOST_PYTHON_MODULE(hello)
{
class_<World>("World")
.def("greet", &World::greet)
.def("set", &World::set)
;
}
int main(int argc, char *argv[])
{
Py_Initialize();
World worldObject;
worldObject.set("Hello, World!");
try {
inithello();
PyRun_SimpleString("import hello");
// ********************
// How would I call the equivalent of:
// worldObject.greet();
// from Python?
// ********************
} catch (error_already_set) {
PyErr_Print();
}
Py_Finalize();
return 0;
}
----------------------------------------
More information about the Cplusplus-sig
mailing list