先介绍第一种方法,python文档中给出了python c api,可以实现C++与python的互动。
在库目录添加python的libs目录,如下(记得查看自己的python安装目录)
此时去你的python安装目录下面,找到libs文件夹,可以看到里面会有好几个lib文件,都是以python+版本号.lib形式命名,python39.lib是给release使用,python39_d.lib是给debug版本使用。这个需要根据你的项目需要release还是debug版本来决定,以debug为例,找到项目->属性->链接器->输入->附加依赖项,添加python39_d.lib完整路径
先编辑python文件,名字:mytest.py,定义了hello函数
# -*- coding: utf-8 -*-
def hello():
print("Hello c++, I'm python!")
再编辑调用python的C++文件,在项目的源文件处中添加main.cpp文件,内容如下
#include <iostream>
#include <python.h>
using namespace std;
void hello()
{
Py_Initialize();
if (!Py_IsInitialized())
{
cout << "Python initialization fails " << endl;
return ;
}
PyObject* pModule = NULL;
PyObject* pFunc = NULL;
pModule = PyImport_ImportModule("mytest"); // 调用的文件名
pFunc = PyObject_GetAttrString(pModule, "hello"); //调用的函数名
PyObject_CallObject(pFunc, NULL); //执行python函数
Py_Finalize();
}
即可,对于python c api如何使用这里就不介绍了,网上很多类似文章。
手机扫一扫
移动阅读更方便
你可能感兴趣的文章