I have written a small Hello World application that uses Python's C-API. The C library requires some functions to be called for global library (de-)initialization and the objects created by the library eventually need to be released by passing the pointer to a specific function. I think this is a fairly common pattern in C libraries.
I attempted to use RAII, to get automatic cleanup, even when exceptions interfere with the planned control flow.
#include <tr1/memory>
#include <Python.h>
// helper to get function pointer for the macro
void Python_DecreaseRefCount(PyObject* p) {
Py_DECREF(p);
}
int main() {
// declare struct and create instance that handles global initialization and
// deinitialization of Python API
static struct PythonApi {
PythonApi() { Py_Initialize(); }
~PythonApi() { Py_Finalize(); }
} python_api;
// create object
// use smart pointer for automatic refcount decrement at scope end
std::tr1::shared_ptr<PyObject> string(
PyString_FromString("Hello World!\n"),
&Python_DecreaseRefCount);
// do something with object
PyObject_Print(string.get(), stdout, Py_PRINT_RAW);
}
Compiles and runs with:
$ g++ test.cc `pkg-config --cflags --libs python2` && ./a.out
Hello World!
I'm interested in all kinds of feedback, as to whether my attempt makes sense and if there is room for improvement. Are there best practices, or certain idioms that facilitate this, that I might have missed in my approach?