(四)c/c++、python混合编程——c/c++调用python第三方包numpy等

1.环境:
win10、VS2017、Anaconda3(python3.x)
说明:
2.步骤:
2.1.在vs2017新建一个空项目,新建文件c_call_python.cppmath_test.pyother.py(c_call_python.cpp调用math_test.py,而math_test.py又导入other.py,other.py里面有第三方包numpy)

//c_call_python.cpp
#include <Python.h>

//把const char *c转 wchar_t * ,作为Py_SetPythonHome()参数匹配
 wchar_t *GetWC(const char *c)
{
    const size_t cSize = strlen(c) + 1;
    wchar_t* wc = new wchar_t[cSize];
    mbstowcs(wc, c, cSize);

    return wc;
}

int main()
{
    //设定参数值
    int a = 0;
    int b = 6;
    //初始化(下面的方法可以在c:\APP\Anaconda3\include\pylifecycle.h中找到)
    //Py_SetProgramName(0);
    //很关键的一步,去掉导入numpy报错
    Py_SetPythonHome(GetWC("C:/APP/Anaconda3"));
    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;

    }
    //很关键的一步,如果是多次导入PyImport_ImportModule模块
    //只有最后一步才调用Py_Finalize(),此时python全局变量一直保存着
    Py_Finalize();
    //方便查看
    while (1);

    return 0;
}
#math_test.py
import other as oth

def add_func(a,b):

    return oth.funx2(a)+b 

def sub_func(a,b):

    return (a-b)
#other.py
import numpy as np
def funx2(a):
    data = [[1,2],[3,4],[5,6]]
    x = np.array(data)
    print(x)
    print("call funx2 numpy2")
    return a*2

2.2编译运行

3.结果:

这里写图片描述

  • 14
    点赞
  • 63
    收藏
    觉得还不错? 一键收藏
  • 59
    评论
评论 59
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值