簡體   English   中英

使用char緩沖區從DLL創建C函數的python回調。

[英]Creating a python callback for a C function from a DLL with a char buffer.

我正在嘗試為C DLL創建一個python包裝器。 C DLL使用回調來通過UDP從DLL“發送”消息。

我期望發生的是python代碼將加載DLL庫和兩個函數。 然后它將使用RegisterCallbackSendMessage函數向DLL RegisterCallbackSendMessage回調。 指向回調的指針將存儲在DLL存儲空間的內存中。 然后python代碼將調用SendWhoIs DLL函數。 此函數將創建一個緩沖區並使用SendMessage函數指針將消息從DLL發送到python代碼。

我遇到的問題是python中的SendMessage函數中的message參數不知道如何解釋void *並且我無法將此緩沖區傳遞給sock.sendto函數。

我收到以下錯誤。

sock.sendto(message, (UDP_IP, UDP_PORT))
TypeError: a bytes-like object is required, not 'int'

我的問題是:如何將c_void_p轉換為sock.sendto可以接受的字節數組。

我盡可能地減少了我的代碼,但仍然可以理解。

這是我的C代碼

// C DLL code 
// 

#define DllExport extern "C" __declspec( dllexport )

typedef uint16_t(*FPCallbackSendMessage)(const uint8_t * message, const uint32_t length);
FPCallbackSendMessage g_CallbackSendMessage;

DllExport bool RegisterCallbackSendMessage(uint16_t(*p_CallbackSendMessage)(const uint8_t * message, const uint32_t length)) {
    g_CallbackSendMessage = p_CallbackSendMessage ; 
    return true;
}

void SendWhoIs(unsigned int dd) {
    printf("dd=%d", dd); 
    char buffer[500];
    g_CallbackSendMessage( buffer, 500 ); 
}

這是我的python代碼

# Python code 
# =================
print("Start") 

customDLL = cdll.LoadLibrary ("customeDLL.dll")

def SendMessage( message, length ):
    print("SendMessage...") 
    UDP_IP = "192.168.1.1"
    UDP_PORT = 47808
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    sock.sendto(message, (UDP_IP, UDP_PORT))
    return True 

print("Registering Callback SendMessage...") 
SendMessageFUNC = CFUNCTYPE(c_bool, c_void_p, c_uint)
SendMessage_func = SendMessageFUNC( SendMessage )

RegisterCallbackSendMessage = customDLL.RegisterCallbackSendMessage
RegisterCallbackSendMessage.argtypes = [ SendMessageFUNC ]
RegisterCallbackSendMessage( SendMessage_func ) 

print("Do message...") 
SendWhoIs = BACnetStackDLL.SendWhoIs
SendWhoIs.argtypes = [c_uint]

SendWhoIs( 47 )

print("End") 

我想到了。

在python SendMessage函數中,我想出了一種將c_void_p轉換為字節數組的方法。

# convert the pointer to a buffer. 
buffer = c_char * length 
messageToSend = buffer.from_address(message)

暫無
暫無

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

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