[Tutor] Python C extension - which method?

eryk sun eryksun at gmail.com
Sun May 6 15:15:37 EDT 2018


On Sun, May 6, 2018 at 12:49 AM, Brad M <thebigwurst at gmail.com> wrote:
> If I may ask, what's the difference between these two?
>
> 1)
> import ctypes
> hello = ctypes.WinDLL('hello', use_last_error=True)
>
> 2)
> from ctypes import cdll
> hello = cdll.LoadLibrary('hello.dll')

Use ctypes.CDLL and ctypes.WinDLL instead of cdll.LoadLibrary and
windll.LoadLibrary. The latter is more typing for no benefit and
prevents using the constructor arguments: handle, mode (POSIX),
use_errno, and use_last_error (Windows). You need the latter two
options if the library requires C errno or Windows GetLastError(), in
which case you should use ctypes.get_errno() or
ctypes.get_last_error() to get the error values after a C function
call.

> Both of them can return "1980" from  this:
>
> hello.c
>
> #include <stdio.h>
>
> __declspec(dllexport) int say_something()
> {
>     return 1980;
> }

CDLL is the cdecl calling convention, and WinDLL is stdcall. There is
no difference in 64-bit Windows (x64 ABI). In 32-bit Windows (x86
ABI), cdecl has the caller clean the stack (i.e. pop arguments), and
stdcall has the callee (the called function) clean the stack. cdecl
allows functions with a variable number of arguments, such as the CRT
printf function. In MSVC, cdecl is the default convention if you don't
declare a function as __stdcall. A library can export functions with
varying calling conventions, so in general you may need to mix CDLL
and WinDLL.


More information about the Tutor mailing list