从python调用C ++ dll

问题描述 投票:2回答:1

我在c ++中创建了一个dll库,并将其导出为c型dll。库头是这样的:library.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);

library.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'

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

python c++ struct dll char
1个回答
0
投票

将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)]

并且将argtypes和实际调用更改为

testDll.argtypes = [POINTER(OutData)]
testDll.Calculation(byref(outData))
© www.soinside.com 2019 - 2024. All rights reserved.