Can you mock a C function using ctypes?

Grant Edwards grant.b.edwards at gmail.com
Thu Sep 15 21:57:47 EDT 2022


On 2022-09-15, Eryk Sun <eryksun at gmail.com> wrote:
> 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().

That's typically not the case.

Does the pointer have to be passed? Or can it be "poked" into a global
variable? If so, I guess it would be fairly trivial to write a dummy
version of bar() in C that calls a function via a global pointer that
could be set via ctypes?

> 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