[Python-Dev] cffi in stdlib (original) (raw)

Armin Rigo arigo at tunes.org
Thu Feb 28 00🔞44 CET 2013


Hi Paul,

On Wed, Feb 27, 2013 at 9:31 PM, Paul Moore <p.f.moore at gmail.com> wrote:

from ctypes import windll MessageBox = windll.User32.MessageBoxW MessageBox(0, "Hello, world!", "Title", 0)

You are right that it's a bit cumbersome in cffi up to and including 0.5, but in the cffi trunk all standard Windows types are included. So the general answer to your question is: we google MessageBox and copy that line from the microsoft site, and manually remove the unnecessary WINAPI and _In_opt declarations:

from cffi import FFI ffi = FFI() ffi.cdef(""" int MessageBox(HWND hWnd, LPCTSTR lpText, LPCTSTR lpCaption, UINT uType); """) lib = ffi.dlopen("USER32.DLL") lib.MessageBox(ffi.NULL, "Hello, world!", "Title", 0)

That's a slightly unfair example, because in this case it happens to work with ctypes without specifying the argtypes and the restype. I would argue that this feature of ctypes is not a good thing: it's mostly the same as saying "you only need to declare argtypes and restype if you get nonsense results or segfaults".

Note for completeness that the version with verify() simply replaces "lib = ffi.dlopen("USER32.DLL")" with "lib = ffi.verify("")" (no #include necessary here). Then you cannot misdeclare anything without getting clear compile-time errors at the verify(). The compilation occurs only once (it's cached) and by writing two lines in your setup.py you can distribute binary installations, just like you do with hand-written C extension modules; so the extra burden of accessing the API level is in my opinion very small compared to its segfault-avoiding gain. But I know that either level of access can make sense in different situations. Typically, on Windows, the ABI-level works fine; as argued elsewhere, on other platforms and/or with some libraries, the API-level is definitely more suited.

A bientôt,

Armin.



More information about the Python-Dev mailing list