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

Lawrence Spector Lawrence.Spector at CanfieldSci.com
Mon Jul 9 23:15:49 CEST 2007


Ah ha.  Now I see.  I quickly tried it and yes, that solved my first issue.  Thanks!

Now moving on, is there a way to add it to the dict without making a copy, but instead having foo be a reference to the instance of MyClass()?

Thanks,

Lawrence

-----Original Message-----
From: c++-sig-bounces at python.org [mailto:c++-sig-bounces at python.org] On Behalf Of Nat Goodspeed
Sent: Monday, July 09, 2007 5:06 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?

> -----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);
_______________________________________________
C++-sig mailing list
C++-sig at python.org
http://mail.python.org/mailman/listinfo/c++-sig



More information about the Cplusplus-sig mailing list