[C++-sig] When You Create an Python Object Using Boost.Python, How Do You Find Out Its Name?

Nat Goodspeed ngoodspeed at solidworks.com
Mon Jul 9 23:05:53 CEST 2007


> -----Original Message-----
> From: c++-sig-bounces at python.org [mailto:c++-sig-bounces at python.org]
On
> Behalf Of Lawrence Spector
> Sent: Monday, July 09, 2007 4:51 PM
> To: Development of Python/C++ integration
> Subject: Re: [C++-sig] When You Create an Python Object Using
> Boost.Python, How Do You Find Out Its Name?
> 
> In your example, it should have a name of foo, which you can call
methods
> on.
> 
> The problem I'm having is I want to be able to create the object using
the
> boost::python wrappers around the Python-C API, but access it from a
> script.
> 
> So, this works:
> 
> foo = MyClass()
> foo.callMethod()
> 
> However, when I do this in C++:
> 
> object foo(MyClass());
> object result = exec("foo.callMethod()", main_namespace,
main_namespace);
> 
> This fails on the second line, with:
>         NameError: name 'foo' is not defined.

[Nat] That's what I would expect, yes. Your "object foo(...)" C++
declaration creates a memory location whose name 'foo' is known to the
C++ compiler at compile time -- but that name vanishes from the program
before it begins execution. It does not create a dict entry "foo" with
which the Python interpreter can look up your new instance.
 
> I guess, the first question would be is: "object foo(MyClass())" the
> equivalent to foo = MyClass()?  If so, how do I make foo the name that
is
> in the dict.  If not, how do I write the equivalent of foo = MyClass()
> using Boost.Python?

[Nat] Assuming that main_namespace is a boost::python::dict, you should
be able to write:

object foo(MyClass()); // s.b. 'object(new MyClass())'? haven't tested
main_namespace["foo"] = foo;
object result = exec("foo.callMethod()", main_namespace,
main_namespace);

Unless you need subsequent C++ references to the new MyClass object, of
course you could abbreviate the above to something like:

main_namespace["foo"] = object(MyClass()); // 'object(new MyClass())' ?
object result = exec("foo.callMethod()", main_namespace,
main_namespace);



More information about the Cplusplus-sig mailing list