OSX上编写C++代码调用Python脚本,编译报错

环境信息

使用Macbook Pro(M1 Pro芯片),OS版本为Monterey 12.2.1。
Python虚拟环境通过conda安装,版本为3.9.7。C++调用Python所使用到的Python头文件和Python动态库是从Python虚拟环境下拷贝而来。
编译器版本信息如下:

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版本为3.22.2。

问题现象

编译代码时,报如下错误:

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

代码

  • python代码
def print_hello():
    print("hello")
  • C++代码
#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脚本
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)

原因分析

问题原因推测为环境上所使用的python动态库文件(libpython3.9.dylib)是macOS-x86_64架构的,而M1 Pro芯片是arm64架构。
但是,如何安装macOS-arm64架构的python动态库,尚未找到答案,请大家看看有什么解决方法。

摸索到解决方法了,我来自问自答吧。
既然通过conda安装的python动态库并非arm64架构,我就在想是不是通过别的安装方式可以获得arm64架构的python动态库。于是,我又用homebrew安装了python,结果还真是被我蒙到了。

xxxx@macbook-pro Current % file Python
Python: Mach-O 64-bit dynamically linked shared library arm64

你好,我是有问必答小助手,非常抱歉,本次您提出的有问必答问题,技术专家团超时未为您做出解答


本次提问扣除的有问必答次数,将会以问答VIP体验卡(1次有问必答机会、商城购买实体图书享受95折优惠)的形式为您补发到账户。


因为有问必答VIP体验卡有效期仅有1天,您在需要使用的时候【私信】联系我,我会为您补发。