一、Python调用C++动态库
实现方法:使用python 的ctypes 模块加载dll
首先,需要用VS创建一个dll动态库,网上方法很多,就不细说了,代码如下:
#include "epsonrobotlibrary_global.h"
class EpsonRobotDriver;
class EPSONROBOTLIBRARY_EXPORT EpsonRobotLibrary
{
public:
~EpsonRobotLibrary();
static EpsonRobotLibrary* Instance();
#pragma region 测试接口
void ShowMsgBox();
int ReturnValue();
#pragma endregion
private:
EpsonRobotLibrary();
private:
EpsonRobotDriver* m_EpsonRobotDriver;
};
extern "C" _declspec(dllexport) int ReturnValue()
{
return EpsonRobotLibrary::Instance()->ReturnValue();
}
extern "C" _declspec(dllexport) void ShowMsgBox()
{
EpsonRobotLibrary::Instance()->ShowMsgBox();
}
然后创建一个python脚本,代码如下:
from ctypes import *
Robot = cdll.LoadLibrary('EpsonRobotLibrary.dll')
def ReturnValue()
print(Robot.ReturnValue())
if __name__ == "__main__":
ReturnValue()
把生成的动态库和脚本放在同一文件夹,然后执行脚本,就可以调用C++动态库里的函数了。
注:虽然按照上述步骤操作了,但是很多时候运行脚本会报“找不到XXX模块的错”,这个时候就需要注意你当前调用的dll是否依赖了别的库,如果有需要把依赖的库一起拷到同一文件夹。
如何查看依赖库,可以使用VS自带工具 x64 Native Tools Command Prompt for VS XXXX(版本号)。
命令:dumpbin /dependents + exe\dll文件路径
二、C++调用Python 脚本
参照文章:C++ 调用python方法 - MasonLee - 博客园 (cnblogs.com)
C++调用python文件(包含第三方库) - 知乎 (zhihu.com)
还是使用之前的脚本,内容如下,命令robotFlow.py
from ctypes import *
Robot = cdll.LoadLibrary('EpsonRobotLibrary.dll')
def ReturnValue()
print(Robot.ReturnValue())
if __name__ == "__main__":
ReturnValue()
创建工程,编写C++代码程序,代码如下:
#include <Python.h>
#include <iostream>
using namespace std;
int main(){
// 1、初始化python接口
Py_Initialize();
if(!Py_IsInitialized()){
cout << "python init fail" << endl;
return 0;
}
// 2、初始化python系统文件路径,保证可以访问到 .py文件
PyRun_SimpleString("import sys");
PyRun_SimpleString("sys.path.append('./')");
// 3、调用python文件名,不用写后缀
PyObject* pModule = PyImport_ImportModule("robotFlow");
if( pModule == NULL ){
cout <<"module not found" << endl;
return 1;
}
// 4、调用函数
PyObject* pFunc = PyObject_GetAttrString(pModule, "ReturnValue");
if( !pFunc || !PyCallable_Check(pFunc)){
cout <<"not found function add_num" << endl;
return 0;
}
//
PyObject_CallObject(pFunc, NULL);
// 5、结束python接口初始化
Py_Finalize();
return 0;
}
直接引入python.h文件肯定会报错的,需要设置相关属性,打开工程属性,做如下设置
注:D:\python3\是你python解释器的安装路径
然后将解释器安装路径下的DLLS,lib两个重要文件夹复制到C++编译exe同目录下。
编译程序,可能会报关于“PyType_Slot”,“PyObject”的错,如下:
解决方法是在object.h文件下添加如下代码
然后执行程序,整个流程就结束了。