Skip to content Skip to sidebar Skip to footer

How To Convert A Callback Result?

I am new to ctypes but I want to create a callback function with the following callback signature: def autosetup_callback(p0, p1, p2): '''This is my callback function signature

Solution 1:

There's some inconsistency in your example:

  • The prototype of your function takes four arguments but you only have three in your Python implementation.
  • __stdcall should use WINFUNCTYPE not CFUNCTYPE.
  • sn is an instance, not a type. The first parameter of the callback definition is the return value (void, None in Python).
  • The last parameter type is char[512] (decays to char* so c_char_p is needed in the callback definition.

Here's a working example. Given:

test.c

#define API __declspec(dllexport)  // Windows-specific exporttypedefint SIndex;
typedefvoid(__stdcall *CALLBACK)(SIndex sIndex, unsignedint statusFlag, unsignedint, constchar message[512]);

CALLBACK g_callback;

API void set_callback(CALLBACK pFunc)
{
    g_callback = pFunc;
}

API void call()
{
    g_callback(1,2,3,"Hello");
}

test.py

from ctypes import *

CALLBACK = WINFUNCTYPE(None,c_int,c_uint,c_uint,c_char_p)

@CALLBACKdefautosetup_callback(p0, p1, p2, p3):
    print('autosetup arguments', p0, p1, p2, p3)

dll = CDLL('test')
dll.set_callback.argtypes = CALLBACK,
dll.set_callback.restype = None
dll.call.argtypes = None
dll.call.restype = None

dll.set_callback(autosetup_callback)
dll.call()

Output:

autosetup arguments123 b'Hello'

Post a Comment for "How To Convert A Callback Result?"