2017-06-21 68 views
0

C++接口: 无符号长_stdcall NAPI_JsonCommand(字符* szCommand,无符号长* pulRet,字符* PBUF,整数nLen,无符号长* pulDevCode);蟒ctypes的回调C++

回调函数的定义: 的typedef长(_stdcall fMsgCallback)(INT NMSG,空隙 pUserData,字符* PBUF,INT nLen,INT nParam);

蟒(3.5.2)码

#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)) 

其结果是,如果使用的话

dict={"KEY":"CONNECTREGISTER","PARAM":{"CALLBACK":CMPFUNC(py_cmp_func),"AUTOPIC":0,"IP":"192.168.150.30","PORT":5556}} 
dicts=json.dumps(dict) 

将是错误的回调函数py_cmp_func不执行

!类型错误:在0x021BB8A0 WinFunctionType对象不是JSON序列化

回调函数的JSON字符串,如何在回调函数的内存地址传递给C++?

回答

0

不知道这会工作,但我看到了两个问题:

addr=hex(id(CMPFUNC(py_cmp_func))) 

在上面的线,CMPFUNC(py_cmp_func)正在执行的行之后销毁,因为会有没有更多的引用。另外,id()给出了CMPFUNC对象的地址,而不是内部函数指针。尝试之一:

callback = CMPFUNC(py_cmp_func) # keep a reference 
addr = addressof(callback)  # Not sure you need hex... 

,或者使用一个装饰,将保持并参考了功能:

@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.