將字串轉換為char*.
import ctypes
from subprocess import Popen, PIPE
# Press the green button in the gutter to run the script.
libname = "c:\temp\debug_api_lib.dll"
c_lib = ctypes.windll.LoadLibrary(libname)
class Gilad(object):
def __init__(self, host, port):
c_lib.menu_function_new.argtypes = [ctypes.c_char_p, ctypes.c_int]
c_lib.menu_function_new.restype = ctypes.c_void_p
c_lib.get_mac_address_new.argtypes = [ctypes.c_void_p]
c_lib.get_mac_address_new.restype = ctypes.c_char_p
c_lib.get_otp_data_new.argtypes = [ctypes.c_void_p]
c_lib.get_otp_data_new.restype = (ctypes.c_char_p * 3)
self.obj = c_lib.menu_function_new(host, port)
def get_mac_address(self):
return c_lib.get_mac_address_new(self.obj)
def get_otp_data(self):
return c_lib.get_otp_data_new(self.obj)
if __name__ == '__main__':
host = "11.11.11.11".encode('utf-8')
t = Gilad(host, 21)
print(t.get_mac_address())
otp_data: object = t.get_otp_data()
for i in otp_data: //the issue is here
print(i)
這是我用 c 風格包裝的 cpp 代碼:
extern "C"
{
__declspec(dllexport) menu_function* menu_function_new(char * host, int port)
{
return new menu_function(host, port);
}
__declspec(dllexport) char* get_mac_address_new(menu_function* menu_function)
{
std::string res_string = menu_function->get_mac_address();
char* res = new char[res_string.size()];
res_string.copy(res, res_string.size(), 0);
res[res_string.size()] = '\0';
return res;
}
__declspec(dllexport) char** get_otp_data_new(menu_function* menu_function)
{
int num = 3;
std::vector<std::string> res_string = menu_function->get_otp_data();
char** res = (char**)malloc(num * sizeof(char**));
for (int i = 0; i < num; i )
{
res[i] = (char*)malloc(res_string[i].size());
res_string[i].copy(res[i], res_string[i].size(), 0);
res[i][res_string[i].size()] = '\0';
}
return res;
}
我可以看到res3 個字串被正確復制,但是在 python 中列印時我得到:b'\xa0y\xa4P\x12\x01'
我想我正在列印指標。
uj5u.com熱心網友回復:
該函式正在回傳 a char**,并且您已經告訴 Python 它正在回傳 a char*[3](一個由 3 個char*指標組成的陣列,而不是一個指標本身),因此回傳的值沒有被 ctypes 正確解釋。
更改回傳型別ctypes.POINTER(ctypes.c_char_p),或者改變你的計劃,以回報的東西,有相同的大小char*[3],如std::array<char*, 3>或struct otp_data { char *one, *two, *three; };(這將是小1個malloc的,因為你可以通過回傳值這個)
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/400656.html
下一篇:C中的malloc和陣列
