Can I create a prototype for a variadic Python function using ctypes so that a DLL can call this function as a callback?

StackOverflow https://stackoverflow.com/questions/13867473

Question

Here's the scenario: I am using ctypes to load a C DLL into a Python program. I want to register a callback so that code in the DLL can call a function in Python.

This is all great until I want to have the function be variadic. For example, say I wanted to implement "printf" in Python (for argument's sake, I'll also have it return an integer):

def printf(format, *args):
    (...)
    return 0

I am creating the callback function pointer using the CFUNCTYPE factory in ctypes:

callback_type = CFUNCTYPE(c_int, c_wchar_p)

Of course, since I only specify one input argument (the format string as a Unicode char array), the callback works but *args is empty.

So, is there any way of making this work with ctypes, or do I need to rewrite my C code to not require a variadic callback function?

Was it helpful?

Solution

No, it's not supported by the underlying libffi. You need indeed to write custom C code.

(Fwiw, CFFI is a ctypes alternative. Also based on libffi, it suffers from the same limitation --- but at least it makes it easy to write custom pieces of C code to do the interfacing.)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top