writing a Python extension module in C++

Guido van Rossum (guido@cwi.nl)
Fri, 07 Feb 1992 16:33:07 +0100

I've forgotten who asked about this, but I've just verified that it is
indeed possible to implement a Python extension module in C++.

All you really need to do is enclose the #includes of Python header
files in extern "C" { ... } and declare the only public C function of
the module (its initialization function) as extern "C". Here's an
example ("trialmodule.C"):

------------------------------------------------------------------------
// An extension module for Python in C++

extern "C" {
#include "allobjects.h"
#include "modsupport.h"
}

static object* trial_test(object*, object* args) {
if (!getnoarg(args)) NULL;
printf("Hello, world!\n");
INCREF(None);
return None;
}

static struct methodlist trial_methods[] = {
{"test", (method)trial_test}, // *** cast! ***
{NULL, NULL}
};

extern "C" void inittrial() {
initmodule("trial", trial_methods);
}
------------------------------------------------------------------------

There's one bit of uneasiness: the function pointer (trial_test) in
the initializer for trial_methods must be cast explicitly to method.
This is because the typedef for method in "methodobject.h" uses the
FPROTO() macro rather than PROTO() (both defined in "PROTO.h") which
makes the function prototype vanish, and C++ then believes it has no
arguments. I may fix this in the next release.

It even works with the new dynamic loading I've added to Python 0.9.6!

Disclaimer: this is on an SGI with a reasonably modern C++ translator,
based on AT&T cfront 2.0. I suppose a restriction will be that you
can't declare global objects with constructors or destructors, since
the Python main program is compiled by C, not by C++.

--Guido van Rossum, CWI, Amsterdam <guido@cwi.nl>
Founder of the Royal Society for Prevention of Cruelty to Amoebae