Reputation: 1
C ++ interface: unsigned long _stdcall NAPI_JsonCommand(char* szCommand, unsigned long* pulRet, char* pBuf, int nLen, unsigned long* pulDevCode);
Callback function definition: typedef long (_stdcall fMsgCallback)(int nMsg, void pUserData, char* pBuf, int nLen, int nParam);
python(3.5.2) code
#coding=utf-8
__author__ = 'wjyang'
import ctypes
from ctypes import *
import json
dll = ctypes.WinDLL("napi.dll")
CMPFUNC=WINFUNCTYPE(c_long,c_int,c_void_p,c_char_p,c_int,c_int)
def py_cmp_func(nMsg,pUserData,pBuf,nLen,nParam):
print("this is callback")
return 1
addr=hex(id(CMPFUNC(py_cmp_func)))
dict={"KEY":"CONNECTREGISTER","PARAM":{"CALLBACK":addr,"AUTOPIC":0,"IP":"192.168.150.30","PORT":5556}}
dicts=json.dumps(dict)
commd=c_char_p(dicts.encode())
print(dll.NAPI_JsonCommand(commd,c_int(0),None,c_int(0),None))
、
The result is that the callback function py_cmp_func is not executed
if used
dict={"KEY":"CONNECTREGISTER","PARAM":{"CALLBACK":CMPFUNC(py_cmp_func),"AUTOPIC":0,"IP":"192.168.150.30","PORT":5556}}
dicts=json.dumps(dict)
will be wrong! TypeError: WinFunctionType object at 0x021BB8A0 is not JSON serializable
Callback function in the json string, how the callback function memory address passed to c ++?
Upvotes: 0
Views: 510
Reputation: 178031
Not sure this will work, but I see two problems:
addr=hex(id(CMPFUNC(py_cmp_func)))
In the above line, CMPFUNC(py_cmp_func)
is destroyed after executing the line because there will be no more references. Also, id()
gives the address of the CMPFUNC
object, not the internal function pointer. Try either:
callback = CMPFUNC(py_cmp_func) # keep a reference
addr = addressof(callback) # Not sure you need hex...
or use a decorator which will keep the reference to the function as well:
@WINFUNCTYPE(c_long,c_int,c_void_p,c_char_p,c_int,c_int)
def py_cmp_func(nMsg,pUserData,pBuf,nLen,nParam):
print("this is callback")
return 1
addr = addressof(py_cmp_func) # Again, not sure about hex.
Upvotes: 0