Use Macbook Pro(M1 Pro chip ),OS Version is Monterey 12.2.1.
Python Virtual environment through conda install , Version is 3.9.7.C++ call Python Used in Python Header files and Python Dynamic library is from Python Copy from the virtual environment .
The compiler version information is as follows :
Configured with: --prefix=/Applications/Xcode.app/Contents/Developer/usr --with-gxx-include-dir=/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/c++/4.2.1
Apple clang version 13.0.0 (clang-1300.0.29.30)
Target: arm64-apple-darwin21.3.0
Thread model: posix
InstalledDir: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin
cmake Version is 3.22.2.
When compiling code , Report the following error :
ld: warning: ignoring file /Users/yangfan/machine_learning/pytorch_cpp/third_party/python/lib/libpython3.9.dylib, building for macOS-arm64 but attempting to link with file built for macOS-x86_64
def print_hello(): print("hello")
#include <iostream>#include <Python.h>using namespace std;bool call_python(){ Py_Initialize(); PyObject* module = PyImport_ImportModule("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(); return 0;}
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)
The cause of the problem is speculated to be the environmental python Dynamic library files (libpython3.9.dylib) yes macOS-x86_64 Architecturally , and M1 Pro The chip is arm64 framework .
however , How to install macOS-arm64 Architecturally python Dynamic library , The answer has not yet been found , Please see if there are any solutions .
I have found a solution , Let me ask and answer myself .
Since we passed conda Installed python Dynamic library is not arm64 framework , I wonder if I can get it through other installation methods arm64 Architecturally python Dynamic library . therefore , And I use homebrew Installed python, The result was that I was really blinded .
xxxx@macbook-pro Current % file Python
Python: Mach-O 64-bit dynamically linked shared library arm64