Can you mock a C function using ctypes?

Eryk Sun eryksun at gmail.com
Thu Sep 15 16:10:21 EDT 2022


On 9/15/22, Grant Edwards <grant.b.edwards at gmail.com> wrote:
>
> Can that be done using ctypes?
>
> For example, I open a library that contains functon foo() where foo()
> calls external function bar() which is not contained in the library.
> Then, I provide a Python bar() function that gets called by foo() when
> foo() is called?

That's straight forward if the library allows the application to pass
a function pointer to bar(). ctypes function prototypes are defined by
ctypes.CFUNCTYPE(restype, *argtypes, use_errno=False,
use_last_error=False) for the cdecl calling convention, or similarly
by ctypes.WINFUNCTYPE() to use the Windows stdcall calling convention.
A prototype can be instantiated as a function pointer that calls a
Python function, e.g. c_bar = prototype(bar).


More information about the Python-list mailing list