[prev in list] [next in list] [prev in thread] [next in thread] 

List:       pykde
Subject:    Re: [PyKDE] SIP: /Array/ and memory deallocation
From:       Phil Thompson <phil () riverbankcomputing ! co ! uk>
Date:       2006-03-22 15:48:58
Message-ID: 200603221548.58502.phil () riverbankcomputing ! co ! uk
[Download RAW message or body]

On Wednesday 22 March 2006 1:43 pm, Giovanni Bajo wrote:
> Hello,
>
> I have an API like this:
>
> class Foo
> {
> public:
>     Foo(char *filename);
>     Foo(char *buffer, int size);
>     [...]
> };
>
> To make both construction forms work, I have wrapped the second constructor
> as a staticmethod factory, using /Array/ and /ArraySize/ (this is because
> overload resolution can't work, as both forms would get a Python string
> object).
>
> The problem is the ownership of the buffer pointer. The C++ Foo API expects
> the buffer to stay alive for the lifetime of the Foo instance. Is there an
> immediate way to implement this? I was thining of storing the buffer as
> Pything string object in a "secret" member of the Foo wrapped instance.
> Does that sound like a good solution?

So you want the Python API to behave differently to the C++ API? Actually, 
somebody else had exactly the same request a few days ago.

The wrapper that SIP generates has a PyObject * field called "user" that you 
can use for whatever you want. Your ctor needs to look something like...

Foo(SIP_PYOBJECT filename) [(char *)]:
%MethodCode
    // Check the argument is a string. You should also handle Py_None.
    char *filename = PyString_AsString(a0);

    if (!filename)
        sipCpp = 0;
    else
    {
        // This might also be sipFoo(filename).
        sipCpp = new Foo(filename);

        sipSelf->user = a0;
        Py_XINCREF(a0);
    }
%End

You have to be careful because the signature will match any call with a single 
argument, so if you have other single argument ctors make sure this is the 
last one.

SIP will manage the reference from then on.

Phil

_______________________________________________
PyKDE mailing list    PyKDE@mats.imk.fraunhofer.de
http://mats.imk.fraunhofer.de/mailman/listinfo/pykde
[prev in list] [next in list] [prev in thread] [next in thread] 

Configure | About | News | Add a list | Sponsored by KoreLogic