[PyKDE] SIP: /Array/ and memory deallocation

Phil Thompson phil at riverbankcomputing.co.uk
Wed Mar 22 15:48:58 GMT 2006


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




More information about the PyQt mailing list