Sometimes I need to get the uncertain length char* string returned in C++ functions. At present, I have found two ideas to solve the problem, and the specific implementation is as follows:
1. Put char* into the structure
The c++ function is as follows:
typedef struct FileData { long long lenth; char* data; }; bool GetData(FileData *data) { if (data == nullptr) { return false; } data->data = new char[255]; memset(data->data, 0, 255); const char* laosi = "wdaweqweqweqweqweqweqweqwdvdggggsdfsferqwerawerqwerqwerqerqwedsd"; memcpy(data->data, laosi, strlen(laosi)); data->lenth = strlen(laosi); return true; }
The python code is as follows:
import ctypes import os import platform from threading import Thread,Lock CharPtr = (ctypes.c_char) class FileData(): _fields_=[ ("lenth",ctypes.c_longlong), ("data",CharPtr) ] FileDataPtr = (FileData) def GetDll(): if ().lower() == 'windows': isWinPlat_ = True else: isWinPlat_ = False currentPath_ = ().replace('\\','/') if isWinPlat_: dll_ = (currentPath_ + '/') else: dll_ = (currentPath_ + '/') return dll_ pytestdll_ = GetDll() def GetData(): getDataF = pytestdll_.GetData =[FileDataPtr] = ctypes.c_bool dataa = FileData() ret = getDataF((dataa)) print() len = for i in range(len): print([i]) charArr = ctypes.c_char* char_arr = charArr(*[:]) print(char_arr.raw) return ret GetData()
2. Use char* as the return value
The c++ code is as follows:
char* GetDatas(long long& lenth) { char* data = new char[255]; memset(data, 0, 255); const char* laosi = "wdaweqweqweqweqweqweqweqwdvdggggsdfsferqwerawerqwerqwerqerqwedsd"; memcpy(data, laosi, strlen(laosi)); lenth = strlen(laosi); return data; }
The python code is as follows:
import ctypes import os import platform from threading import Thread,Lock CharPtr = (ctypes.c_char) class FileData(): _fields_=[ ("lenth",ctypes.c_longlong), ("data",CharPtr) ] FileDataPtr = (FileData) def GetDll(): if ().lower() == 'windows': isWinPlat_ = True else: isWinPlat_ = False currentPath_ = ().replace('\\','/') if isWinPlat_: dll_ = (currentPath_ + '/') else: dll_ = (currentPath_ + '/') return dll_ pytestdll_ = GetDll() def GetDataS(): getDatasF = pytestdll_.GetDatas =[(ctypes.c_longlong)] = ctypes.c_char_p lengths = ctypes.c_longlong(0) ret = getDatasF((lengths)) print() print(ret) GetDataS()
This is the introduction to this article about the two ideas of obtaining the char* field returned in C++ in Python. For more related contents of obtaining the C++ C++ return to the char* field, please search for my previous articles or continue browsing the following related articles. I hope everyone will support me in the future!