(四)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 

//把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.结果:

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

你可能感兴趣的:(python)