How to convert a callback result?

2019-08-28 17:32发布

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
void(__stdcall *pGUIFunction)(SIndex sIndex, unsigned int statusFlag, unsigned int, const char message[512])    
    """     
    print('autosetup arguments', p0, p1, p2)


sn= c.c_uint(0)
autosetup_cb_format = c.CFUNCTYPE(sn, c.c_uint, c.c_uint, c.c_char)

When this callback is called, I get the following errors:

    File "_ctypes/callbacks.c", line 257, in 'converting callback result'

TypeError: an integer is required (got type NoneType)

settings: values p1,p2,p3: 0 0 0
autosetup arguments 0 0 b'\x18' ### This is what the callback should print
Exception ignored in: <function autosetup_callback at 0x000001E3D4135A60>

Any ideas?

1条回答
Melony?
2楼-- · 2019-08-28 18:10

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 export

typedef int SIndex;
typedef void(__stdcall *CALLBACK)(SIndex sIndex, unsigned int statusFlag, unsigned int, const char 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)

@CALLBACK
def autosetup_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 arguments 1 2 3 b'Hello'
查看更多
登录 后发表回答