[C++-sig] Handle class and lifetime

Tom Brooks tbrooks.mail at gmail.com
Mon Jul 2 00:36:16 CEST 2007


I'm a beginner at this but, I find that it's easiest and most effective to
simply use boost::shared_ptr to hold anything. You can get Python to hold it
in a boost::shared_ptr, too, by putting boost::shared_ptr<graph> into the
template of the "graph" class_. Like so:

class_<graph, boost::shared_ptr<graph> > pyg("graph")

Then, just use boost::shared_ptr or boost::weak_ptr everywhere in C++ that
you need to reference the graph. It's straight-forward and I find that it
eliminates the ownership-struggle between Python and C++ that I frequently
get.

Hope that helps you.

On 6/29/07, Anders Wang Kristensen <awk at imm.dtu.dk> wrote:
>
> Hi,
>
> I'm a little confused by the call policies in boost python.
>
> I have something like the following situation:
>
> struct vertex
> {
>    graph* p;
>    int x;
> };
>
> struct graph
> {
>    vertex get_vertex(int i);
> };
>
> and in my python module:
>
> class_<graph> pyg("graph")
> pyg.def("get_vertex", &graph::get_vertex,
>    with_custodian_and_ward_postcall<0,1>());
>
> Is this the right way to make sure that graphs wont be destroyed while
> there are still vertices around which reference these graphs?
>
> Thanks!
>
> -- Anders
>
> _______________________________________________
> C++-sig mailing list
> C++-sig at python.org
> http://mail.python.org/mailman/listinfo/c++-sig
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/cplusplus-sig/attachments/20070701/f656691d/attachment.htm>


More information about the Cplusplus-sig mailing list