1

I am trying to create Python extension module that combine both C++ and Python code. So far I was able to run Python code fine but I can’t find a way for my Python object to appear as part of my module import. What am I doing wrong?

Here the example code for my C++ module (I am omitting C++/boost::python code that bind C++ function and classes for clarity):

#include <boost/python.hpp>
BOOST_PYTHON_MODULE( my_module ) { 
  <... some boost::python code to bind C++ classes/functions ...>
  boost::python::object main_module = boost::python::import("__main__");
  boost::python::object main_namespace = main_module.attr("__dict__”);
  boost::python::exec("aaa = 'ABC’\n”, main_namespace, main_namespace);
}

And later in Python if I try:

import my_module
print my_module.aaa  <— error!

(I know that I can separate python files and C++ dynamic libs in to its own files and it will all work, but i really need my extension module to be just one file for other technical reasons)

1 Answer 1

1
boost::python::scope().attr("aaa")="ABC";
Sign up to request clarification or add additional context in comments.

2 Comments

Yes, i know about this workaround but i really want to execute arbitrary Python code (developed by third parties) as part of my module. So far i even tried to create dummy submodule, execute python in it and copy all objects back - its almost works ("import something" and "from something import thing" does not got copied that way)
@WorkPerNap: But you're modifying the main module's namespace, not my_module's namespace.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.