简体   繁体   中英

Calling C++ dll from python

I have a created dll library in c++ and exported it as c type dll. The library header is this: 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;
}

Now I have this Python script:

#! 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)

When I print the fields from outData I get the same results in all of them:

b'surfReq'

b'surfReq'

b'surfReq'

Can you please tell me how to specify the char arrays/fields so I get the correct result. I am only allowed to change the python script. I called this library from C# with no problems.

Changed the python ctypes to 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)]

And changed the argtypes and actual call to

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM