本文介绍了如何解决“分段故障”C&放大器时混合编程;蟒蛇?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的Ubuntu的:

Under my Ubuntu:

$猫test.py

$ cat test.py

#Filename test.py
def Hello():
    print "Hello, world!"

$猫tom.cpp

$ cat tom.cpp

#include <Python.h>

int main()
{
     Py_Initialize();

     PyObject * pModule = NULL;
     PyObject * pFunc   = NULL;

     pModule = PyImport_ImportModule("test");
     pFunc   = PyObject_GetAttrString(pModule, "Hello");
     PyEval_CallObject(pFunc, NULL);

     Py_Finalize();

     return 0;
}

和再编译:

g++ tom.cpp -I/usr/include/python2.7 -L/usr/lib/python2.7 -lpython2.7

运行:
$ ./a.out

Run:$ ./a.out

Segmentation fault

为什么呢?
谁能帮助吗?
谢谢!

Why?Could anyone help?Thanks!

BR,
汤姆

BR,Tom

推荐答案

该问题是由PyObject_GetAttrString返回NULL引起的。我还增加了使用PyRun_SimpleString的目录路径为我的dev目录不蟒蛇下路径

the issue is caused by PyObject_GetAttrString returning NULL. I have also added the directory path using PyRun_SimpleString as my dev dir was not under python path

#include <Python.h>

int main()
{

    Py_Initialize();
    PyRun_SimpleString ("import sys; sys.path.insert(0, 'add the directory path here')");
    PyObject * pModule = NULL;
    PyObject * pFunc   = NULL;

    pModule = PyImport_ImportModule("test");
    pFunc   = PyObject_GetAttrString(pModule, "Hello");
    if(pFunc != NULL) {
        PyEval_CallObject(pFunc, NULL);
        Py_Finalize();
    }
    else {
        printf("pFunc returned NULL\n");
    }

    return 0;
}

这篇关于如何解决“分段故障”C&放大器时混合编程;蟒蛇?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 08:50
查看更多