从C ++调用Python函数

时间:2022-09-06 21:32:41

I am trying to make a call to a python module function from my cpp file.

我试图从我的cpp文件调用python模块函数。

The call i have made is as follows:

我的电话如下:

#include <iostream>
#include "Python.h"

int
main(int argc, char** argv)
{
    Py_Initialize();
    PyObject *pName = PyString_FromString("tmpPyth");
    PyObject *pModule = PyImport_Import(pName);
    std::cout<< "Works fine till here";
    PyObject *pDict = PyModule_GetDict(pModule);
    if (pModule != NULL) {
        PyObject *pFunc = PyObject_GetAttrString(pDict, "pyFunc");

        if(pFunc != NULL){
            PyObject_CallObject(pFunc, NULL);
        }
    }
    else
        std::cout << "Python Module not found";
    return 0;
}

My python module is defined as follows:

我的python模块定义如下:

import numpy
import scipy
import matplotlib

from scipy import stats
def blah():
        baseline = [9.74219, 10.2226, 8.7469, 8.69791, 9.96442, 9.96472, 9.37913, 9.75004]
        follow_up = [9.94227,9.46763,8.53081,9.43679,9.97695,10.4285,10.159,8.86134]
        paired_sample  = stats.ttest_rel(baseline , follow_up )
        print "The t-statistic is %.3f and the p-value is %.3f." % paired_sample

The code in the cpp file runs fine till the 1st "std::cout" but then ends up giving me a "seg fault". Running the python code separately works fine and gives the desired output.

cpp文件中的代码运行正常,直到第一个“std :: cout”,但最后给我一个“seg fault”。单独运行python代码可以正常工作并提供所需的输出。

I cant figure out what is going wrong. Any help will be appreciated. (Note the program is compiling correctly and running correctly till the 1st "cout")

我无法弄清楚出了什么问题。任何帮助将不胜感激。 (注意程序正在正确编译并正确运行,直到第一个“cout”)

1 个解决方案

#1


So there are a couple of things that you were not doing right. See the comments inline. Assuming that both your CPP file and Python file lives at the following path: /home/shanil/project.

所以有几件事你做得不对。请参阅内联评论。假设您的CPP文件和Python文件都位于以下路径:/ home / shanil / project。

test.cpp:

#include <iostream>
#include "Python.h"

int
main(int argc, char** argv)
{
    Py_Initialize();

    // First set in path where to find your custom python module.
    // You have to tell the path otherwise the next line will try to load
    // your module from the path where Python's system modules/packages are
    // found.
    PyObject* sysPath = PySys_GetObject("path");
    PyList_Append(sysPath, PyString_FromString("/home/shanil/project"));

    // Load the module
    PyObject *pName = PyString_FromString("my_mod");
    PyObject *pModule = PyImport_Import(pName);

    // Random use-less check
    std::cout<< "Works fine till here\n";

    if (pModule != NULL) {
        std::cout << "Python module found\n";

        // Load all module level attributes as a dictionary
        PyObject *pDict = PyModule_GetDict(pModule);

        // Remember that you are loading the module as a dictionary, the lookup you were
        // doing on pDict would fail as you were trying to find something as an attribute
        // which existed as a key in the dictionary
        PyObject *pFunc = PyDict_GetItem(pDict, PyString_FromString("my_func"));

        if(pFunc != NULL){
            PyObject_CallObject(pFunc, NULL);
        } else {
            std::cout << "Couldn't find func\n";
        }
    }
    else
        std::cout << "Python Module not found\n";
    return 0;
}

my_mod.py:

def my_func():
    print 'got called'

#1


So there are a couple of things that you were not doing right. See the comments inline. Assuming that both your CPP file and Python file lives at the following path: /home/shanil/project.

所以有几件事你做得不对。请参阅内联评论。假设您的CPP文件和Python文件都位于以下路径:/ home / shanil / project。

test.cpp:

#include <iostream>
#include "Python.h"

int
main(int argc, char** argv)
{
    Py_Initialize();

    // First set in path where to find your custom python module.
    // You have to tell the path otherwise the next line will try to load
    // your module from the path where Python's system modules/packages are
    // found.
    PyObject* sysPath = PySys_GetObject("path");
    PyList_Append(sysPath, PyString_FromString("/home/shanil/project"));

    // Load the module
    PyObject *pName = PyString_FromString("my_mod");
    PyObject *pModule = PyImport_Import(pName);

    // Random use-less check
    std::cout<< "Works fine till here\n";

    if (pModule != NULL) {
        std::cout << "Python module found\n";

        // Load all module level attributes as a dictionary
        PyObject *pDict = PyModule_GetDict(pModule);

        // Remember that you are loading the module as a dictionary, the lookup you were
        // doing on pDict would fail as you were trying to find something as an attribute
        // which existed as a key in the dictionary
        PyObject *pFunc = PyDict_GetItem(pDict, PyString_FromString("my_func"));

        if(pFunc != NULL){
            PyObject_CallObject(pFunc, NULL);
        } else {
            std::cout << "Couldn't find func\n";
        }
    }
    else
        std::cout << "Python Module not found\n";
    return 0;
}

my_mod.py:

def my_func():
    print 'got called'