Creating custom Python objects from C code

Stefan Behnel stefan_ml at behnel.de
Wed Jan 5 13:42:06 EST 2011


Eric Frederich, 05.01.2011 17:27:
> I have read through all the documentation here:
>
>      http://docs.python.org/extending/newtypes.html
>
> I have not seen any documentation anywhere else explaining how to
> create custom defined objects from C.

At this point, it is best to take a look at Cython *before* continuing your 
struggle to solve problems that you wouldn't even have become aware of if 
you had used it right away.


> I have this need to create custom objects from C and pass them as
> arguments to a function call.
>
> Question 1: how am I to create those objects from C code?

In Cython:

    obj = SomeType()

or (in some truly performance critical cases):

    obj = SomeType.__new__(SomeType)


> The other thing I would like to know is how I can create helper
> functions in my extension so they can be created and manipulated
> easily.

Either functions or static methods would work here. It's up to you to make 
a suitable design choice.


> I am thinking along the lines of the built-in helper functions
> PyList_New and PyList_Append.
> Once I have an answer to question 1, the problem won't be creating the
> helper functions, but making them available from something built with
> distutils.
> To use the builtin python functions from C I need to link against
> python27.lib but when I create my own package using distutils it
> creates dll or pyd files.

Cython has an embedding mode ("--embed" option) that generates a suitable 
main() function to embed the Python interpreter in your module. That might 
work for you as is, or it will at least show you the required C code that 
you can adapt as you see fit.


> Question 2: How do I make C helper functions that are part of my
> extension available to other C projects in the same way that PyList_*,
> PyString_*, PyInt_* functions are available?

Cython allows you to mark C functions and Python extension types with the 
"api" keyword and generates suitable header files and import/export code 
for them that you can use both from C and from other Cython generated 
modules. It automatically uses PyCObject in older Python versions and 
PyCapsule in Py2.7 and Py3.1+.

Stefan




More information about the Python-list mailing list