[C++-sig] call_method

David Abrahams dave at boost-consulting.com
Sun Nov 10 04:15:10 CET 2002


"Brett Calcott" <brett.calcott at paradise.net.nz> writes:

> Hi all,
>
> (Sorry for the delay in getting back David)
>
>> Have you tried adding a call to
>>
>>    implicitly_convertible<py_agent_ptr,agent_ptr>()
>>
>
> Damn. I Should have found that really...
> It works fine now. Yay!
>
> However, the example I hacked up displays a weird bug. The virtual function
> returns a char const *, and when I subclass this in python and return a
> string it throws an error:
>
> ReferenceError: Attempt to return dangling pointer to object of type: char
> V:/src/boost_python_test/test>python test.py
>
> ...but only if there is a space in the string returned. This must be some
> weird side effect. Or returning a char const * from python may just be plain
> dodgy. 

It's not exactly dodgy, but you have to be somewhat careful. When you
convert from a Python string to a char const*, you're getting a
pointer to the internals of that Python object. If the Python object
you're pointing into has only a single reference (because it's the
unique return value of the function you just called), then by the time
your C++ function returns it will have zero references. At that point
your char const* will be pointing at invalid memory. The library is
protecting you by throwing an exception instead.

Read all about it at
http://www.boost.org/libs/python/doc/v2/callbacks.html#result_handling

So if you're going to return a char const*, you'd better be sure it
points into some object that you know will persist past the
call. Returning std::string instead works much more uniformly, because
a C++ std::string owns its resources.


<snip>

> and the python:
>
> import simple
>
> e = simple.engine()
>
> class my_agent(simple.py_agent):
>     def do_something(self):
>         # return "my agent here" ******CRASH****
>         return "my_agent_here" # this is okay

Note: this is not a ******CRASH****, since you got a nice Python
exception out of it. A ******CRASH**** looks like a core dump or other
unrecoverable program error <wink>

-- 
                       David Abrahams
   dave at boost-consulting.com * http://www.boost-consulting.com
Boost support, enhancements, training, and commercial distribution





More information about the Cplusplus-sig mailing list