[C++-sig] Whats going on under the hood?

David Sveningsson ext at sidvind.com
Thu Jan 18 14:51:59 CET 2007


David Sveningsson skrev:
> Roman Yakovenko skrev:
>   
>> On 1/18/07, David Sveningsson <eXt at sidvind.com> wrote:
>>   
>>     
>>> I want to understand how python/boost handles the memory.
>>>
>>> Take a look at the following code:
>>>
>>> void add(Base& e){
>>>      list->add(e);      // Permanently stores the object
>>> }
>>>
>>> BOOST_PYTHON_MODULE(Foo){
>>>      def("add", &add);
>>>
>>>      class_<Base>("Base")
>>>
>>>      ;
>>> }
>>>
>>> and this:
>>>
>>> class Derived (Foo.Base):
>>>      pass
>>>
>>> add(Derived())
>>>
>>> What happens when this code is run? What happens when the python scope
>>> ends? May I safely use the reference in C++? Should I delete the
>>> reference afterwards? What happens if I delete the reference, does it
>>> delete memory allocated from python too?
>>>     
>>>       
>> Did you read tutorials?
>> http://boost.org/libs/python/doc/tutorial/doc/html/python/functions.html#python.call_policies
>>
>>
>>   
>>     
> Yes, but what I don't understand is what really happens in my example.
> Since I didn't specify a return policy it's not safe to use the
> reference in C++, but what call policy should I use? I cannot tie the
> return value to the arguments like in the tutorial. Maybe I
> missunderstand the call policies.
>
>   
I've been reading about taking ownership of raw pointers as described in
http://www.boost.org/libs/python/doc/v2/faq.html#ownership

However, I won't get it to work.
My code:

void add(std::auto_ptr<Base> e){
     list->add(e.get());
     print(list);
     e.release();
}

BOOST_PYTHON_MODULE(Foo){
     def("add", &add);

     class_<Base, std::auto_ptr<Base> >("Base")

     ;
}

Python:

class Derived (Foo.Base):
     pass

a = Derived()
add(a)
a = Derived()
add(a)

When I instance the class the second time and add it, it crashes when trying to print the content of the list. Most likely because the pointer is corrupt, which means python still did release the instance.

What I heard many times is with_custodian_and_ward but I cannot get it to work.

"def("add", &add, with_custodian_and_ward<1, 1>() );" fails to compile with the error "boost::STATIC_ASSERTION_FAILURE<false>"
"def("add", &add, with_custodian_and_ward<1, 2>() );" fails at runtime with "boost::python::with_custodian_and_ward: argument index out of range"

I just want python to give up trying to manage the memory and transfer the ownership to C++ completely.

 




-- 


//*David Sveningsson [eXt]*

Freelance coder | Game Development Student
http://sidvind.com

Thou shalt make thy program's purpose and structure clear to thy fellow man by using the One True Brace Style, even if thou likest it not, for thy creativity is better used in solving problems than in creating beautiful new impediments to understanding.




More information about the Cplusplus-sig mailing list