Reputation: 574
I am learning to embed python code into c++ code. Following the simple example in How to solve the 'Segmentation fault' when hybrid programming of C & Python? and use g++ main.cpp -I/usr/include/python2.7 -L/usr/lib/python2.7 -lpython2.7
to compile the code and run the program, I can get the correct result.
But if I create a "build" folder and using CMake to run the program, it still has segmentation fault.
My CMakeList.txt is like below:
cmake_minimum_required(VERSION 2.8)
project ( pyTest )
if(NOT CMAKE_BUILD_TYPE)
set(CMAKE_BUILD_TYPE "RELEASE")
endif()
string(ASCII 27 Esc)
set(Red "${Esc}[1;31m")
set(ColourReset "${Esc}[m")
if(CMAKE_BUILD_TYPE MATCHES "DEBUG")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++0x -O0 -g")
MESSAGE(STATUS "${Red}BUILD TYPE: DEBUG${ColourReset}")
else()
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++0x -O3")
MESSAGE(STATUS "${Red}BUILD TYPE: RELEASE${ColourReset}")
endif()
include_directories( include )
find_package(PythonLibs REQUIRED)
include_directories(${PYTHON_INCLUDE_DIRS})
set(SRC_LIST2 main.cpp)
add_executable( pytest ${SRC_LIST2})
target_link_libraries(pytest ${PYTHON_LIBRARIES})
For convenience, I post my code below:
pytest.py
def Hello():
print "Hello, world!"
main.cpp
#include <Python.h>
int main()
{
Py_Initialize();
PyRun_SimpleString ("import sys; sys.path.insert(0, 'DIRECTORY_PATH'");
PyObject * pModule = NULL;
PyObject * pFunc = NULL;
pModule = PyImport_ImportModule("pytest");
pFunc = PyObject_GetAttrString(pModule, "Hello");
if(pFunc != NULL) {
PyEval_CallObject(pFunc, NULL);
Py_Finalize();
}
else {
printf("pFunc returned NULL\n");
}
return 0;
}
where "DIRECTORY_PATH" is the folder path of my main.cpp file and pytest.py, not the path of "build" folder
When I print out the result of PyImport_ImportModule, it returns 0. I think that means it doesn't get the python model. But my main.cpp and python file are under same directory, I don't know why it cannot get the model...
Can I fix it? Thx!
Upvotes: 1
Views: 1260
Reputation: 574
Solved by myself. I should put main.cpp and pytest.py under same directory and use PyRun_SimpleString ("import sys; sys.path.insert(0, 'DIRECTORY_PATH'");
to change 'DIRCTORY_PATH' to current directory that saves main.cpp and pytest.py. (Before I used a wrong dirctory so I got segmentation fault)
Upvotes: 1