Here is howto: Exporting a Class from a .pyd

Gerson Kurz gerson.kurz at
Fri Jul 6 14:36:48 EDT 2001

Task: export a class from a .pyd

1) Forget about, it contains horrible C++ code like this:
namespace boost { namespace python { namespace detail {
struct function::type_object:singleton<function::type_object,
type_object() : singleton_base(&PyType_Type) {}};
And that was the readable bit of it.

2) In the initXYZ() routine, store a pointer to the module object
returned, e.g.

PyObject* my_module;

my_module = Py_InitModule4( "SampleClass", SampleClass_methods,
SampleClass_docstring, NULL, PYTHON_API_VERSION );

3) Create some methods. Here is one:

static PyObject* func_SampleMethod( PyObject* self, PyObject* args )
    return PyInt_FromLong(42);

4) Create a class object. Its not documented, and the header says /*
Revealing some structures (not for general use) */ but I'm not in the
military so I guess it is for my use, anyway.

static PyObject* func_SampleClass( PyObject* self, PyObject* args )
    // name of the class
    PyObject* pName = PyString_FromString( "SampleClass" );

    // Create the __dict__ of the class. This example just adds a
    // single method copied from the global module dict.
    PyObject* pDict = PyDict_New();
    PyObject* pModuleDict = PyModule_GetDict(my_module);

    return PyClass_New( NULL, pDict, pName );

The NULL paramter could be replaced by a tuple of base classes. Note
that this function will create a *class* object, not an instance

5) In Python, do things like

import SampleClass

s = SampleClass.SampleClass()
print type(s), dir(s)

o = s()
print o.SampleMethod()

Ah, I love python !

More information about the Python-list mailing list