簡體   English   中英

python ctypes回調c ++

[英]python ctypes callback c++

C ++接口: unsigned long _stdcall NAPI_JsonCommand(char * szCommand,unsigned long * pulRet,char * pBuf,int nLen,unsigned long * pulDevCode);

回調函數定義: typedef long(_stdcall fMsgCallback)(int nMsg,void pUserData,char * pBuf,int nLen,int nParam);

python(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))

結果是未執行回調函數py_cmp_func

如果使用

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

會錯的! TypeError:位於0x021BB8A0的WinFunctionType對象不是JSON可序列化的

在json字符串中有回調函數,該回調函數的內存地址如何傳遞給c ++?

不確定是否可以,但是我看到兩個問題:

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.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM