[C++-sig] Calling member function of object created in C++ via embedded Python

Roman Yakovenko roman.yakovenko at gmail.com
Fri Apr 13 19:43:24 CEST 2007


On 4/13/07, Ron Brown, Jr. <rbrown at gamry.com> wrote:
>  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.

There are few resources to look for information. One of them is:
http://wiki.python.org/moin/boost.python/EmbeddingPython
You can find more complete list here:
http://language-binding.net/pyplusplus/links.html#help-resources

>
> 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

You definitely  should continue to read tutorials:
http://www.boost.org/libs/python/doc/tutorial/doc/html/python/object.html

And finally the answer to your question is here:
http://www.boost.org/libs/python/doc/v2/call_method.html


> ----------------------------------------
> #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?
>                 // ********************

namespace bpl = boost::python;
bpl::object py_wo( World() );
bpl::call_method<void >(py_wo, "set", "Hello World");

I think this should work


 --
Roman Yakovenko
C++ Python language binding
http://www.language-binding.net/



More information about the Cplusplus-sig mailing list