Linux下C++调用Python的简单实现

参考链接:https://blog.csdn.net/u012983289/article/details/55194714

Python脚本如下:

def printHelloWold():
    print('hello world')

def add(a, b):
    c = a+b
    return c

C++代码如下:

#include <iostream>
#include "Python.h"
using namespace std;

// 简易版本
void method1()
{
    Py_Initialize();
    PyRun_SimpleString("import sys");
    PyRun_SimpleString("sys.path.append('./')");
    PyRun_SimpleString("import pytest");
    PyRun_SimpleString("pytest.printHelloWold()");
    Py_Finalize();
}

// 初级版本
void method2()
{
    Py_Initialize();
    PyRun_SimpleString("import sys");
    PyRun_SimpleString("sys.path.append('./')");
    PyObject *pModule = NULL;
    PyObject *pFunc = NULL;
    pModule = PyImport_ImportModule("pytest");                 //Python文件名
    pFunc = PyObject_GetAttrString(pModule, "printHelloWold"); //Python文件中的函数名
    PyEval_CallObject(pFunc, NULL);                            //调用函数,NULL表示参数为空
    Py_Finalize();                                             //Py_Finalize,和Py_Initialize相对应的.
}

// 带参数和返回值版本
void method3()
{
    Py_Initialize();
    PyRun_SimpleString("import sys");
    PyRun_SimpleString("sys.path.append('./')");
    PyObject *pModule = NULL;
    PyObject *pFunc = NULL;
    pModule = PyImport_ImportModule("pytest");      //Python文件名
    pFunc = PyObject_GetAttrString(pModule, "add"); //Python文件中的函数名
    //创建参数:
    PyObject *pArgs = PyTuple_New(2);                 //函数调用的参数传递均是以元组的形式打包的,2表示参数个数
    PyTuple_SetItem(pArgs, 0, Py_BuildValue("i", 6)); //0--序号,i表示创建int型变量
    PyTuple_SetItem(pArgs, 1, Py_BuildValue("i", 8)); //1--序号
    //返回值
    PyObject *pReturn = NULL;
    pReturn = PyEval_CallObject(pFunc, pArgs); //调用函数
    //将返回值转换为int类型
    int result;
    PyArg_Parse(pReturn, "i", &result); //i表示转换成int型变量
    cout << "6 + 8 = " << result << endl;
    Py_Finalize();
}

int main()
{
    // 简易版本
    method1();

    // 初级版本
    method2();
    
    // 带参数和返回值版本
    method3();
    
    return 0;
}

CMakeLists.txt内容如下:

cmake_minimum_required( VERSION 2.8 )
project ( code_test )

set( CMAKE_CXX_COMPILER "g++" )
set( CMAKE_BUILD_TYPE "Debug" )
set( CMAKE_CXX_FLAGS "-std=c++11 -O0" )

include_directories(
    /usr/include/python3.6m
)

link_directories(
    /usr/lib/x86_64-linux-gnu
)

add_executable( run_test test.cpp )
target_link_libraries(run_test
    libpython3.6m.so
)

如果用gcc,则相当于:

 g++ test.cpp -I /usr/include/python3.6m -L /usr/lib/x86_64-linux-gnu -lpython3.6m

输出如下:

hello world
hello world
6 + 8 = 14

说明程序编译运行成功。

我曾经尝试调用Anaconda的Python,但是经过各种尝试还是失败,所以暂且使用系统自带的Python吧。

  • 6
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值