Swig deferencing python temporaries in typemap

Question:

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?

Asked By: Henrique Bucher

||

Answers:

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

Answered By: Mark Tolonen
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.