[C++-sig] Passing a reference to my object to python

Roman Yakovenko roman.yakovenko at gmail.com
Tue Jul 3 20:53:44 CEST 2007


On 7/3/07, Lawrence Spector <Lawrence.Spector at canfieldsci.com> wrote:
> So far, what I've done is build a Boost.Python extension for my python
> script to use.  It exposes one class for the script to use, let's say
called
> CppClass.  This seems to work okay.  I'm using Boost.Python and the Python
> API to interpret the script from C++ code.  During this process, I want to
> pass a reference to an instance of the object that already exists in my
C++
> code.  I tried the following:
>
> boost::python::object myObject(CppClass);
>
>
>  When I run, I get a first chance exception:
> boost::python::error_already_set.
>
>
>
> I'm sure I'm missing something important.  Any idea what's going wrong?

I will try to clarify, but I could be wrong.

The default behavior of the object constructor is to copy the object. If you
want it to keep reference to existing object, than you should use boost::ref
or boost::python::ptr functionality.

I also found another method to create object - using call policies:

template< typename CallPolicies, class T >
bpl::object make_object( T x ){
    //constructs object using CallPolicies result_converter
    typedef BOOST_DEDUCED_TYPENAME CallPolicies::result_converter:: template
apply< T >::type result_converter_t;
    result_converter_t rc;
    return bpl::object( bpl::handle<>( rc( x ) ) );
}

You select call policy and it handles for you the conversion. The method
doesn't work in all cases. It will not work if post_call function, of the
call policies class does some job.

It is not clear to me why you get exception. You should provide additional
information.

-- 
Roman Yakovenko
C++ Python language binding
http://www.language-binding.net/
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/cplusplus-sig/attachments/20070703/04fdbe6d/attachment.htm>


More information about the Cplusplus-sig mailing list