Ubuntu16.04下C++调用Python3.5程序
Python程序
import sys
def call():
print("hello world")
if __name__ = '__main__':
call()
C++代码
#include <iostream>
#include <boost/python.hpp>
using namespace std;
using namespace boost::python;
int main()
{
Py_Initialize();
if (!Py_IsInitialize())
{
cout << 'Fail 1' << endl;
return -1;
}
Pyrun_SimpleString("import sys")
int argc = 1;
wchar_t argv[1];
argv[0] = L"/home/tyl/code/call.py";
PySys_setArgv(argc,argv);
if (PyRun_SimpleString("exec(open('/home/tyl/code/call.py').read())"))
{
cout << "Fail 2" <<endl;
return -1;
}
Py_Finalize();
return 0;
}
CMakeLists文件
cmake_minimum_required(VERSION 2.6)
project(test)
set (CMAKE_BUILD_TYPE Debug)
find_package(Boost COMPONENTS thread serialization python REQUIRED)
include_directories(${Boost_INCLUDE_DIR}
/usr/include/python3.5)
add_executable(test main.cpp)
target_link_libraries(test
${Boost_LIBRARIES}
/usr/lib/x86_64-linux-gnu/libboost_python-py35.so
/usr/lib/x86_64-linux-gnu/libstdc++.so.6
/usr/lib/x86_64-linux-gnu/libpython3.5m.so
)
install(TARGETS test RUNTIME DESTINATION bin)