简体   繁体   English

从 python 调用 C++ dll

[英]Calling C++ dll from python

I have a created dll library in c++ and exported it as c type dll.我在 c++ 中创建了一个 dll 库,并将其导出为 c 类型 Z06416233FE5EC4C5933122E4。 The library header is this: library.h库 header 是这样的: 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图书馆.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:现在我有这个 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)

When I print the fields from outData I get the same results in all of them:当我从 outData 打印字段时,我在所有这些字段中得到相同的结果:

b'surfReq' b'surfReq'

b'surfReq' 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.我只能更改 python 脚本。 I called this library from C# with no problems.我从 C# 调用这个库没有任何问题。

Changed the python ctypes to c_char * 10 :将 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)]

And changed the argtypes and actual call to并将 argtypes 和实际调用更改为

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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