简体   繁体   中英

Embedding Python to C++ Receiving Error Segmentation fault (core dumped)

This is my first go at Embedding Python in C++.

I am just trying to create a simple program so I understand how it works.

The following is my code.

main.cpp

#define PY_SSIZE_T_CLEAN
#include </usr/include/python3.8/Python.h>
#include <iostream>


int main(int argc, char *argv[]){
    
    PyObject *pName, *pModule, *pFunc, *pArgs, *pValue;

    Py_Initialize();


    pName = PyUnicode_FromString((char*)"script");
    pModule = PyImport_Import(pName);
    pFunc = PyObject_GetAttrString(pModule, (char*)"test");
    pArgs = PyTuple_Pack(1, PyUnicode_FromString((char*)"Greg"));
    pValue = PyObject_CallObject(pFunc, pArgs);
    
    auto result = _PyUnicode_AsString(pValue);
    std::cout << result << std::endl;

    Py_Finalize();

      

}

script.py

def test(person):
    return "What's up " + person;

This is how I have been compiling on Linux

g++ -I/usr/include/python3.8/ main.cpp -L/usr/lib/python3.8/config-3.8-x86_64-linux-gnu -lpython3.8 -o output

I am compiling like this because (#include <Python.h> has been giving me troubles, Yes I have tried sudo apt-get install python3.8-dev)

The file compiles successfully but when I try to run ./output I receive the following error.

Segmentation fault (core dumped)

I searched up what this error means and it is saying that Segmentation fault is a specific kind of error caused by accessing memory that “does not belong to you.”

But which memory does not belong to me? Is it the python file?

Any Guidance would be much appreciated.

After each and every one of those statements, you will need to check for errors, using something of the form:

if (varname == NULL) {
    cout << “An error occured” << endl;
    PyErr_Print();
    return EXIT_FAILURE;
 }

This will check if the python layer through an error; and if so will ask it to print the Python traceback to the screen, and exit. You can use this traceback to figure out what your error is.

Any of those functions can fail, and you need to check for failure before you continue. Using the Python C API is extremely fiddly because of this. Most C API functions that return a pointer return NULL on error, and passing NULL into any function without checking it first is bound to result in a crash.

You get a segmentation fault from accessing a NULL pointer, as nearly all modern systems map access of NULL to a segmentation fault or crash of some sort to catch programming errors.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM