Because I want to use python Implement a neural network , And embedded in C++ In the code , So I did some research on how to C++ Call in python Methods .
example.cpp Is as follows :
#include <iostream>
#include <Python.h>
using namespace std;
bool call_python_func()
{
Py_SetPythonHome(L"/opt/homebrew/Cellar/[email protected]/3.9.10/Frameworks/Python.framework/Versions/Current");
Py_Initialize();
if (!Py_IsInitialized()) {
cout << "initialization is failed." << endl;
return false;
}
// add python file path
PyRun_SimpleString("import sys");
PyRun_SimpleString("sys.path.append('../')");
PyObject* module = PyImport_ImportModule("print_test");
if (module == nullptr) {
cout << "module is NULL." << endl;
return false;
}
PyObject* func = PyObject_GetAttrString(module, "print_hello");
if (func == nullptr) {
cout << "function is NULL." << endl;
return false;
}
PyEval_CallObject(func, nullptr);
Py_Finalize();
return true;
}
int main(int argc, const char* argv[])
{
call_python_func();
return 0;
}
print_test.py Is as follows :
def print_hello():
print("hello world")
CMakeLists.txt Is as follows :
cmake_minimum_required(VERSION 3.0 FATAL_ERROR)
project(example)
include_directories(../third_party/python/include/python3.9)
link_directories(../third_party/python/lib)
add_executable(example example.cpp)
target_link_libraries(example python3.9)
set_property(TARGET example PROPERTY CXX_STANDARD 14)
example
|- src
|- build
|- example.cpp
|- print_test.py
|- CMakeLists.txt
|- third_party
|- python
|- include
|- lib
among ,example/third_party/python The files in the directory are from python From the installation directory .include Where is the python The header file ,lib The contents are python Dynamic library files .
The compiled script is as follows :
cd build
cmake ..
make