I have a Python module that I import from my C++ code (I'm embedding Python). This module contains a function create() that I want to get a hold of in my C++ code (i.e. store it in a boost::python::object instance).
Here's what I tried. A run-time error occurs on the indicated line in my C++ code. The error occurs because it is unable to find the "hero.create" function inside the main namespace.
C++ code
namespace python = boost::python;
// Standard Boost.Python code
// Here I just create objects for the main module and its namespace
python::object main_module(
python::handle<>(python::borrowed(PyImport_AddModule("__main__")))
);
python::object main_namespace(main_module.attr("__dict__"));
// This is my code
//
python::exec("import hero", main_namespace, main_namespace);
python::object func(main_namespace["hero.create"]); // Run-time error
Entity ent = python::extract<Entity>(func());
// I also tried doing this, but it didn't work either...
// python::object func(main_namespace["hero"].attr("__dict__")["create"]);
// However, if I do this, all works fine...
// python::exec("from hero import create", main_namespace, main_namespace);
// python::object func(main_namespace["create"]); // No error
Python code (hero.py)
from entity import Entity
def create():
ent = Entity()
# ...
return ent
hero.__dict__? Did you try justmain_namespace["hero"].attr("create")? I'd bet you don't useclass.memberto access it from C.