程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

C++ calling Python code on OSX

編輯:Python

​​​​​​​​​​​​​​​​​​​​​ Preface

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 .

environmental information

Software Version information OSOSX Montery 12.2.1(M1 Pro chip )gccapple clang 13.0.0cmake3.22.2python3.9.10
  • If you use conda install python, Then the installed python The dynamic library file is x86_64 Architecturally , While using homebrew Installed python Included in python The dynamic library file is arm64 framework .

Code

C++ Code

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;
}

python Code

print_test.py Is as follows :

def print_hello():
print("hello world")

cmake Script

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)

Code directory structure

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 .

compile

The compiled script is as follows :

cd build
cmake ..
make


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved