0

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
1
  • What do you get if you print out hero.__dict__? Did you try just main_namespace["hero"].attr("create")? I'd bet you don't use class.member to access it from C. Commented Jul 25, 2011 at 12:00

1 Answer 1

3

You need to do main_namespace["hero"].attr("create"). Import creates only one name in the namespace, and it's a module object. Names cannot have dots in them — . is a getattr operator — so hero.create is the same as getattr(hero, 'create').

You could also use boost::python::import directly, instead of execing import statement.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the answer and also for the tip regarding python::import. It looks much cleaner now. :)
I opened a follow-up question (6816373). Could you please take a look at it, if you are willing to?

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.