如何从C+;调用使用numpy的Python函数+;代码

如何从C+;调用使用numpy的Python函数+;代码,python,c++,numpy,Python,C++,Numpy,我有以下Python模块(我想要使用的实际模块,有更多使用numpy和tensorflow的函数),但这是一个再现该问题的代表性示例 import numpy as np def get_random(): return np.random.random() < P>我想从下面的C++程序调用函数GETYNORT: #include <Python.h> #include <stdio.h> #include <string.h> int mai

我有以下Python模块(我想要使用的实际模块,有更多使用
numpy
tensorflow
的函数),但这是一个再现该问题的代表性示例

import numpy as np

def get_random():
    return np.random.random()
< P>我想从下面的C++程序调用函数GETYNORT:

#include <Python.h>
#include <stdio.h>
#include <string.h>

int main(int argc, char *argv[]){

    Py_Initialize();
    if( !Py_IsInitialized() ){
        printf("Initialize failed\n");
        return -1;
    }
    PyRun_SimpleString("import sys");
    //append path of numpy lib
PyRun_SimpleString("sys.path.append('/home/uji300/.pyenv/versions/venv/lib/python3.4/site-packages/numpy/core/include')");
    PyObject *pName, *pModule, *pDict, *pFunc, *pArgs, *pRet;

    pName = PyUnicode_DecodeFSDefault("numpytester");

    pModule = PyImport_Import(pName);
    if ( !pModule ){
        return -1;
    }
    pDict = PyModule_GetDict(pModule);
    if ( !pDict ){
        return -1;
    }
    pFunc = PyDict_GetItemString(pDict, "get_random");
    if ( !pFunc || !PyCallable_Check(pFunc) ){
        return -1;
    }

    for( int i = 0; i < 5; ++i ){
        printf(" ===========> START CALL PYTHON SCRIPT %d <===========\n", i + 1);
        pRet = PyObject_CallObject(pFunc, NULL);     // call the function
        printf(" ===========> CALLING FINISHED  %d <===========\n", i + 1);

        double result = PyFloat_AsDouble(pRet);            // get the return value by pRet
        printf(" ===========> result = %f <===========\n", result);
    }

    Py_DECREF(pName);
    Py_DECREF(pModule);
    Py_DECREF(pArgs);
    Py_DECREF(pRet);
    Py_DECREF(pDict);

    // close Python
    Py_Finalize();
    return 0;
}
#包括
#包括
#包括
int main(int argc,char*argv[]){
Py_初始化();
如果(!Py_已初始化()){
printf(“初始化失败\n”);
返回-1;
}
PyRun_SimpleString(“导入系统”);
//numpy lib的附加路径
PyRun_SimpleString(“sys.path.append('/home/uji300/.pyenv/versions/venv/lib/python3.4/site packages/numpy/core/include');
PyObject*pName、*pModule、*pDict、*pFunc、*pArgs、*pRet;
pName=PyUnicode_decodefsfdefault(“numbytester”);
pModule=PyImport\u Import(pName);
if(!pModule){
返回-1;
}
pDict=PyModule_GetDict(pModule);
如果(!pDict){
返回-1;
}
pFunc=PyDict_GetItemString(pDict,“get_random”);
如果(!pFunc | | |!PyCallable_Check(pFunc)){
返回-1;
}
对于(int i=0;i<5;++i){
printf(“=============>开始调用PYTHON脚本%d调用已完成的%d结果=%f