python调用c++类_Python与C++之间的相互调用实例3: 在Python中调用C++的结构体和类...

这篇博客介绍了如何在Python中调用C++的类和结构体。通过创建C++的结构体和类,将其导出到DLL,然后在Python中使用ctypes库进行调用。文章详细展示了C++结构体和类的定义,以及Python中如何封装对应类以进行调用,并给出了实例代码。
摘要由CSDN通过智能技术生成

之前在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)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值