Calling C++ dll from python
Calling C++ dll from python
我有一个用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))
相关文章:
- 如何运行位于boost/libs/python/example/tutorial目录中的hello.cpp和Jamfil
- Pybind11:将元组列表从Python传递到C++
- 如何在c++中使用引用实现类似python的行为
- 是否可以通过C++扩展强制多个python进程共享同一内存
- 递归列出所有目录中的C++与Python与Ruby的性能
- IPC使用多个管道和分支进程来运行Python程序
- 从python中调用C++函数并获取返回值
- Python 3.7 和 excess_args 的 SWIG 问题
- Python中的for循环与C++有何不同
- Calling C++ dll from python
- Calling Python Script from Visual Studio C++ Solution
- Calling cv::cuda::HOG from python
- 返回 vector<pair<int,int>> & from c++ 方法到 python 使用 swig typemap 的元组列表
- Python Callback from SWIG PyObject_Call Segfault
- Call python from javascript
- calling int main() from python
- Call Python from C++ OpenCV 3.0
- 访问 std::complex<> from gdb python macro
- SEGUID from python to c++
- Python callback from C++