(三)c/c++、python混合编程——c/c++调用python实现加法

1.环境:
win10、VS2017、Anaconda3(python3.x)
2.步骤:
2.1.在vs2017新建一个空文件testpy3,新建文件test.cmath_test.py

//test.c
#include <Python.h>

int main(int argc, char *argv[])
{
    //设定参数值
    int a=3;
    int b=6;
    //初始化
    Py_SetProgramName(argv[0]);
    Py_Initialize();
    //测试python3的打印语句
    PyRun_SimpleString("print('Hello Python!')\n");
    //执行import语句,把当前路径加入路径中,为了找到math_test.py
    PyRun_SimpleString("import os,sys");
    PyRun_SimpleString("sys.path.append('./')");
    //测试打印当前路径
    PyRun_SimpleString("print(os.getcwd())");

    PyObject *pModule;

    PyObject *pFunction;

    PyObject *pArgs;

    PyObject *pRetValue;
    //import math_test
    pModule = PyImport_ImportModule("math_test");

    if(!pModule){

        printf("import python failed!!\n");

        return -1;

    }
    //对应math_test.py中的def add_func(a,b)函数
    pFunction = PyObject_GetAttrString(pModule, "add_func");

    if(!pFunction){

       printf("get python function failed!!!\n");

       return -1;

    }
    //新建python中的tuple对象
    pArgs = PyTuple_New(2);

    PyTuple_SetItem(pArgs, 0, Py_BuildValue("i", a));

    PyTuple_SetItem(pArgs, 1, Py_BuildValue("i", b));
    //调用函数
    pRetValue = PyObject_CallObject(pFunction, pArgs);
    //python3中只有long,PyLong_AsLong(python2中是PyInt_AsLong)
    printf("%d + %d = %ld\n",a,b,PyLong_AsLong(pRetValue));

    Py_DECREF(pModule);

    Py_DECREF(pFunction);

    Py_DECREF(pArgs);

    Py_DECREF(pRetValue);

    if(!pModule){

        printf("import python failed!!\n");

        return -1;

    }

    Py_Finalize();
    //方便查看
    while(1);

    return 0;
}
//math_test.py
def add_func(a,b):

    return a+b

def sub_func(a,b):

    return (a-b)

3.编译

cl test.c -I C:\APP\Anaconda3\include C:\APP\Anaconda3\libs\python36.lib

4.编译后得到test.exe文件
运行得到
这里写图片描述

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值