有时候需要获取C++函数中返回来的不定长的char*字符串,目前我找到两种解决问题的思路,具体实现如下:
一,将char*放入结构体中
c++函数如下:
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;
}
python代码如下:
import ctypes
import os
import platform
from threading import Thread,Lock
CharPtr = ctypes.POINTER(ctypes.c_char)
class FileData(ctypes.Structure):
_fields_=[
("lenth",ctypes.c_longlong),
("data",CharPtr)
]
FileDataPtr = ctypes.POINTER(FileData)
def GetDll():
if platform.system().lower() == 'windows':
isWinPlat_ = True
else:
isWinPlat_ = False
currentPath_ = os.getcwd().replace('\\','/')
if isWinPlat_:
dll_ = ctypes.CDLL(currentPath_ + '/PyTest.dll')
else:
dll_ = ctypes.CDLL(currentPath_ + '/PyTest.so')
return dll_
pytestdll_ = GetDll()
def GetData():
getDataF = pytestdll_.GetData
getDataF.argtypes=[FileDataPtr]
getDataF.restype = ctypes.c_bool
dataa = FileData()
ret = getDataF(ctypes.byref(dataa))
print(dataa.lenth)
len = dataa.lenth
for i in range(len):
print(dataa.data[i])
charArr = ctypes.c_char*dataa.lenth
char_arr = charArr(*dataa.data[:dataa.lenth])
print(char_arr.raw)
return ret
GetData()
二,将char*作为返回值
c++代码如下:
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;
}
python代码如下:
import ctypes
import os
import platform
from threading import Thread,Lock
CharPtr = ctypes.POINTER(ctypes.c_char)
class FileData(ctypes.Structure):
_fields_=[
("lenth",ctypes.c_longlong),
("data",CharPtr)
]
FileDataPtr = ctypes.POINTER(FileData)
def GetDll():
if platform.system().lower() == 'windows':
isWinPlat_ = True
else:
isWinPlat_ = False
currentPath_ = os.getcwd().replace('\\','/')
if isWinPlat_:
dll_ = ctypes.CDLL(currentPath_ + '/PyTest.dll')
else:
dll_ = ctypes.CDLL(currentPath_ + '/PyTest.so')
return dll_
pytestdll_ = GetDll()
def GetDataS():
getDatasF = pytestdll_.GetDatas
getDatasF.argtypes=[ctypes.POINTER(ctypes.c_longlong)]
getDatasF.restype = ctypes.c_char_p
lengths = ctypes.c_longlong(0)
ret = getDatasF(ctypes.byref(lengths))
print(lengths.value)
print(ret)
GetDataS()