[C++-sig] (no subject)

Stefan Seefeld seefeld at sympatico.ca
Wed Oct 12 02:46:10 CEST 2005


jan.walter.berlin at t-online.de wrote:
> Hi,
> 
> Here is a question about Boost.Python and embedding/extending:
> 
> I would like to read a Python script from a file within a plugin of a 3D 
> application. The Python script should contain some commands (functions) 
> which are NOT part of Python but should be implemented in C++ within the 
> SAME plugin. I've read the Tutorial Introduction ( 
> http://www.boost.org/libs/python/doc/tutorial/doc/html/index.html ) and 
> understand how to extend Python (creating a shared library) and how to 
> use the interpreter from within my plugin (embedding) but how can I mix 
> both approaches?
> 
> Something like this:
> 
> #include <Python.h>
> ...
> #include <boost/python.hpp>
> using namespace boost::python;
> ...
> char const* greet()
> {
>   return "hello, world";
> }
> 
> BOOST_PYTHON_MODULE(hello)
> {
>   def("greet", greet);
> }
> ...
> void myCallback()
> {
> ...
>   Py_Initialize();
>   object main_module((handle<>(borrowed(PyImport_AddModule("__main__")))));

I believe you are missing

PyImport_AppendInittab("hello", inithello);

>   object main_namespace = main_module.attr("__dict__");
>   handle<> result((allow_null(PyRun_String(
>                        "import greet\n"

And the above should be "import hello.greet\n".

>                        "print hello.greet()",
>                        Py_file_input,
>                        main_namespace.ptr(),
>                        main_namespace.ptr()))));
>   if (!result) PyErr_Print();
> ...
>   Py_Finalize();

Don't use Py_Finalize() right now. See
http://www.boost-consulting.com/boost/libs/python/todo.html#pyfinalize-safety.

In case you can use boost.python from HEAD (i.e. fresh from the repository),
you may want to look into the boost/libs/python/test/exec.cpp test that
shows how to do the above in a much more compact form, using a new API:

   if (PyImport_AppendInittab("hello", inithello) == -1)
     throw std::runtime_error("Failed to add hello to the interpreter's "
			     "builtin modules");
   // Retrieve the main module
   python::object main = python::import("__main__");

   // Retrieve the main module's namespace
   python::object global(main.attr("__dict__"));

   // Run the inlined script.
   python::object result = python::exec(
     "import hello.greet                  \n"
     "print hello.greet()                 \n",
     global, global);


HTH,
		Stefan



More information about the Cplusplus-sig mailing list