Calling C++ dll from python

Calling C++ dll from python

本文关键字:python from dll C++ Calling      更新时间:2023-10-16

我有一个用c ++创建的dll库,并将其导出为c类型dll。库标头是这样的:图书馆.h

struct Surface
{
char surfReq[10];
};
struct GeneralData
{
Surface surface;
char weight[10];
};
struct Output
{
GeneralData generalData;
char message[10];
};
extern "C" __declspec(dllexport) int __cdecl Calculation(Output &output);

图书馆.cpp

int Calculation(Output &output)
{
strcpy_s(output.message, 10, "message");
strcpy_s(output.generalData.weight, 10, "weight");
strcpy_s(output.generalData.surface.surfReq, 10, "surfReq");
return 0;
}

现在我有了这个 Python 脚本:

#! python3-32
from ctypes import *
import sys, os.path
class StructSurface(Structure):
_fields_ = [("surfReq", c_char_p)]
class StructGeneralData(Structure):
_fields_ = [("surface", StructSurface),
("weight", c_char_p)]
class OutData(Structure):
_fields_ = [("generalData", StructGeneralData),
("message", c_char_p)]
my_path = os.path.abspath(os.path.dirname(__file__))
path = os.path.join(my_path, "../../../libs/Python.dll")
testDll = cdll.LoadLibrary(path)
surfReq = (b''*10)
structSurface = StructSurface(surfReq)
weight = (b''*10)
structGeneralData = StructGeneralData(structSurface, weight)
message = (b''*10)
outData = OutData(structGeneralData, message) 
testDll.restyp = c_int
testDll.argtypes = [byref(outData)]
testDll.Calculation(outData)
print(outData.message)
print(outData.generalData.weight)
print(outData.generalData.surface.surfReq)

当我从outData打印字段时,我得到的结果都相同:

b'surfReq'

b'surfReq'

b'surfReq'

你能告诉我如何指定字符数组/字段,以便我得到正确的结果吗?我只被允许更改 python 脚本。 我从 C# 调用了这个库,没有问题。

将 python ctypes 更改为c_char * 10

class StructSurface(Structure):
_fields_ = [("surfReq", c_char * 10)]
class StructGeneralData(Structure):
_fields_ = [("surface", StructSurface),
("weight", c_char * 10)]
class OutData(Structure):
_fields_ = [("generalData", StructGeneralData),
("message", c_char * 10)]

并将参数类型和实际调用更改为

testDll.argtypes = [POINTER(OutData)]
testDll.Calculation(byref(outData))