Mar*_*cze 5 python clang libclang
我想开始使用libclang和Python。我正在尝试获取在Windows上工作的示例代码( http://www.altdevblogaday.com/2014/03/05/implementing-a-code-generator-with-libclang/ ) ,这是代码的一部分我正在尝试运行:
#!/usr/bin/python
# vim: set fileencoding=utf-8
import sys
import os
import clang.cindex
import itertools
...
print("Setting clang path")
# I tried multiple variations. Libclang is correctly installed in the specified location.
#clang.cindex.Config.set_library_path('C:/Program Files (x86)/LLVM/bin')
#clang.cindex.Config.set_library_path('C:/Program Files (x86)/LLVM/bin/libclang.dll')
# I also tried moving the dll into the Python installation folder.
clang.cindex.Config.set_library_file('C:/Python27/DLLs/libclang.dll')
print("Clang path set")
index = clang.cindex.Index.create()
...
Run Code Online (Sandbox Code Playgroud)
我删除了代码的所有其他部分,但如果它们相关,我可以发布它们。线路
index = clang.cindex.Index.create()
Run Code Online (Sandbox Code Playgroud)
抛出以下错误:
Setting clang path
Clang path set
Traceback (most recent call last):
File "D:\libclangtest\boost_python_gen.py", line 60, in <module>
index = clang.cindex.Index.create()
File "D:\libclangtest\clang\cindex.py", line 2095, in create
return Index(conf.lib.clang_createIndex(excludeDecls, 0))
File "D:\libclangtest\clang\cindex.py", line 141, in __get__
value = self.wrapped(instance)
File "D:\libclangtest\clang\cindex.py", line 3392, in lib
lib = self.get_cindex_library()
File "D:\libclangtest\clang\cindex.py", line 3423, in get_cindex_library
raise LibclangError(msg)
clang.cindex.LibclangError: [Error 193] %1 is not a valid Win32 application. To provide a path to libclang use Config.set_library_path() or Config.set_library_file().
Run Code Online (Sandbox Code Playgroud)
这是什么原因呢?是不是我的dll路径设置错了?我尝试了多种方法,使用正斜杠和反斜杠,我还尝试将 dll 移出程序文件以使路径不包含空格,但没有任何效果。
我是 libclang 和 Python 的初学者,抱歉,如果我问一些微不足道的问题。
我遇到了类似的问题(Windows 7 x64、Anaconda3 x64)。使用
import clang.cindex
clang.cindex.Config.set_library_file('C:/Program Files/LLVM/bin/libclang.dll')
Run Code Online (Sandbox Code Playgroud)
解决了问题。请注意,您需要使用斜杠(而不是反斜杠),并指定bin/libclang.dll的路径(而不是 lib/libclang.dll)。
@SK-logic评论说我应该检查 Python 和 libclang 是32bit 还是 64bit。Libclang是32位的,但是我找不到方法来检查我的Python安装是32位还是64位,所以我重新安装了32位版本,现在它可以工作了。所以问题可能是我使用的是 64 位版本的 Python。