如何解决clang的Python绑定加载错误?

Siy*_*Ren 6 c++ python macos dll clang

我正在尝试针对 clang 的 Python 绑定。我homebrew在 Mac OS X Maverics 上使用命令行安装了 LLVM 及其 python 绑定

 brew install llvm --with-clang --with-python --with-lld
Run Code Online (Sandbox Code Playgroud)

加载代码是

import clang
import clang.cindex

clang.cindex.Config.set_library_path('/usr/local/Cellar/llvm/3.5.0/lib')
index = clang.cindex.Index.create()
Run Code Online (Sandbox Code Playgroud)

但这会引发错误:

clang.cindex.LibclangError: dlopen(/usr/local/Cellar/llvm/3.5.0/lib/libclang.dylib, 6): 库未加载:@rpath/libLLVM-3.5.dylib 引用自:/usr/local/ Cellar/llvm/3.5.0/lib/libclang.dylib 原因:找不到图像。要提供 libclang 的路径,请使用 Config.set_library_path() 或 Config.set_library_file()。

但我不明白为什么会出现这个错误。@rpath这里不是指/usr/local/Cellar/llvm/3.5.0/lib吗?但有一个名为libLLVM-3.5.dylib该目录下。为什么此加载会导致错误以及如何修复它?

Mac*_*ski 1

一个强大的替代方案是使用Config.set_library_path, 在交互式 Python(IPython、Jupyter)中也很有效。

from clang.cindex import Index,Config,CursorKind

# check where is LLVM installed on your machine (here on MacOS)
Config.set_library_path('/usr/local/Cellar/llvm/16.0.3/lib')

SCRIPT_PATH = './tcpdump/print-ppp.c'

# C99 is a proper compiler for tcpdump, as per their docs
index = Index.create()
translation_unit = index.parse(SCRIPT_PATH, args=['-std=c99'])
Run Code Online (Sandbox Code Playgroud)

文档中也推荐这样做。