2017-06-21 3 views
0

C++ Interface: longue _stdcall NAPI_JsonCommand non signé (char * szCommand, unsigned long * pulRet, char * pBuf, int nLen, long * pulDevCode non signé);python ctypes callback C++

définition de la fonction de rappel: typedef longue (_stdcall fMsgCallback) (int NMSG, vide 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)) 

,

Le résultat est que la fonction de rappel py_cmp_func n'est pas exécutée

si elle est utilisée

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

sera mauvais ! TypeError: l'objet WinFunctionType à 0x021BB8A0 n'est pas sérialisable JSON

Fonction de rappel dans la chaîne json, comment l'adresse de la fonction de rappel a-t-elle été transmise à C++?

Répondre

0

Je ne sais pas cela fonctionnera, mais je vois deux problèmes:

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

Dans la ligne ci-dessus, CMPFUNC(py_cmp_func) est détruite après l'exécution de la ligne parce qu'il n'y aura plus de références. En outre, id() donne l'adresse de l'objet CMPFUNC, pas le pointeur de fonction interne. Essayez soit:

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

ou utiliser un décorateur qui gardera la référence à la fonction ainsi:

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