Search code examples
pythoncswig

Swig deferencing python temporaries in typemap


I want to pass a Python datetime object to the function printme below, seamlessly.

struct DateTime {
    uint64_t epochns;
};
void printme(DateTime dt);

So far I was able to create this SWIG typemap to convert from datetime to DateTime

%typemap(in)  DateTime
{
    PyObject* str = PyString_FromString( "timestamp" );
    PyObject* obj = PyObject_CallMethodObjArgs( $input, str, nullptr );
    $1.epochns = PyLong_AsLong( obj );
}

My question is: am I leaking the variables str and obj? Do I need to dereference them?


Solution

  • Both PyString_FromString and PyObject_CallMethodObjArgs are documented to return a new reference, so both str and obj must be released via Py_DECREF or Py_XDECREF or you will leak two references.