之前在C++中写的程序,绝大多数都是用类来封装的。
那么现在想要在Python中进行调用,开始的时候是个头疼的问题。经过将近一天的摸索学习,大概搞明白了一些。
下面贴出来一个例子看一下。
首先是C++的结构体和类:#pragma once #include // 这个结构体在Python中定义后可以通用 struct struHeadPose { float angleX; float angleY; float angleZ; }; // 这个类在Python中定义后可以通用 class pyClass { public: int a; int b; int c; char* str; }; // 这是一个功能类 class myClass { public: myClass(); ~myClass(); void setPos(struHeadPose tPos); void setPose(float x, float y, float z); struHeadPose getPose(); int LoadModel(std::string tStrName); void setPYC(pyClass& tIn); void getPYC(pyClass& tOut); private: struHeadPose m_pos; std::string m_str; pyClass m_pyc; };
cpp很简单,可以自己实现一下就行了。
然后将上面的内容导出到dll中。具体看上一篇:https://blog.csdn.net/sdust_dx/article/details/80606297#include "FileCpp.h" #include "PySEGY.h" #define DLLEXPORT __declspec(dllexport) #define C_DLL_EXPORT extern "C" __declspec(dllexport) extern "C" { DLLEXPORT void __stdcall setPos1(struHeadPose tPos); DLLEXPORT void __stdcall setPos2(float x, float y, float z); DLLEXPORT void __stdcall getPos(struHeadPose& tPos); DLLEXPORT int __stdcall loadModel(char* tStrName); DLLEXPORT void __stdcall setPYC(pyClass tIn); DLLEXPORT void __stdcall getPYC(pyClass& tOut); }
然后在python中调用即可。下面是在python中封装了对应的类(结构体),即可进行调用。
有几个注意问题我写在注释中了。import ctypes import sys sys.path.append('./') myDll = ctypes.CDLL('./HelloCpp2.dll') myDll.Hello() myDll.display() myDll.display_int(1) myDll.setPara(1,2) print('sum=',myDll.getSum()) class structPos(ctypes.Structure): #ctypes 的格式定义结构体 _fields_ = [("X", ctypes.c_float),("Y", ctypes.c_float),("Z", ctypes.c_float)] sModelPath = ctypes.c_char_p(b"MyString[Can only contain ASCII literal characters.]") # 使用 ctypes.c_char_p 可以传递字符串到C++中 ret = myDll.loadModel(sModelPath) print("load model = ", ret) tPos0 = structPos(1.0, 2.0, 3.0) print('tPos0=', str(tPos0)) myDll.setPos1(ctypes.byref(tPos0)) #ctypes 的格式来调用tPos0结构体(类) tPos1 = structPos(0,0,0) myDll.getPos(ctypes.byref(tPos1)) print(tPos1) print ('tPos1.X = ', tPos1.X) print ('tPos1.Y = ', tPos1.Y) print ('tPos1.Z = ', tPos1.Z) print ('tPos0.X = ', tPos0.X) print ('tPos0.Y = ', tPos0.Y) print ('tPos0.Z = ', tPos0.Z) print('TEST --- CLASS') class testClass(ctypes.Structure): #ctypes 的格式定义结构体 _fields_ = [("X", ctypes.c_float),("Y", ctypes.c_float),("Z", ctypes.c_float), ("str", ctypes.c_char_p)] tClass1 = testClass(4,5,6,sModelPath) myDll.setPYC(ctypes.byref(tClass1)) tClass2 = testClass() myDll.getPYC(ctypes.byref(tClass2)) print ('tClass2.X = ', tClass2.X) print ('tClass2.Y = ', tClass2.Y) print ('tClass2.Z = ', tClass2.Z) print(tClass2.str)