[Python-3000] Ctypes as cross-interpreter C calling interface (original) (raw)

Guido van Rossum guido at python.org
Fri Aug 11 02:56:47 CEST 2006


On 8/10/06, Paul Prescod <paul at prescod.net> wrote:

> I don't know enough about ctypes, but assuming I have a reason to > write an extension in C (e.g. Tkinter, which uses the Tcl/Tk API), how > to I use ctypes to call things like PyDictGetItem() or > PyErrSetString()?

There are two answers to your question. The simplest is that if you have a dict object called "foo" you just call 'foo["abc"]'. It's just Python. Same for the other one: you'd just call 'raise'.

That doesn't make sense if you want to write your extension in C. Surely you don't propose to rewrite all of tkinter.c in Python? That would be insane. Or Numeric? That would kill performance.

Ctypes is the opposite model of the standard extension stuff. You're writing in Python so Python stuff is straightforward (just Python) and C stuff is a bit weird. So if you had to populate a Python dictionary from a C struct then it is the reading from the C struct that takes a bit of doing. The writing the Python dictionary is straightforward.

If there was a reason to call PyDictGetItem directly (performance maybe???) then that's possible. You need to set up the function prototype (which you would probably do in a helper library) and then you just call PyDictGetItem. CTypes would coerce the types. pyobject is a native data type. So I think it ends up looking like from PythonConvenienceFunctions import PyDictGetItem obj = {} key = "Guido" rc = PyDictGetItem(obj, key) I'm sure an expert will correct me if I'm wrong...

I guess I object against the idea that we have to write all extensions in Python using ctypes for all C calls. This is okay if there's relatively little interaction with C code. It's insane if you're doing serious C code. And what about C++ extensions?

-- --Guido van Rossum (home page: http://www.python.org/~guido/)



More information about the Python-3000 mailing list