5

I would like to get started with using libclang with Python. I am trying to get a sample code (http://www.altdevblogaday.com/2014/03/05/implementing-a-code-generator-with-libclang/) to work on Windows, here is a part of the code I'm trying to run:

#!/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()

...

I stripped all the other parts of the code, but I can post them if they are relevant. The line

index = clang.cindex.Index.create()

Throws the following error:

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().

What is the reason for this? Am I setting the dll's path wrong? I tried multiple ways, with foreslashes and backslashes, I also tried to move the dll out of Program Files to make the path contain no spaces, but nothing worked.

I am a total beginner to libclang and Python, sry if I'm asking something trivial.

4

2 回答 2

5

I was running into a similar problem (Windows 7 x64, Anaconda3 x64). Using

import clang.cindex
clang.cindex.Config.set_library_file('C:/Program Files/LLVM/bin/libclang.dll')

fixed the problem. Please note that you need to use slashes (not antislashes), and specify path to bin/libclang.dll (not to lib/libclang.dll).

于 2018-05-15T11:27:47.170 回答
4

@SK-logic commented that I should check whether both Python and libclang are either 32bit or 64bit. Libclang was 32bit, but I couldn't find a way to check whether my Python installation is 32 or 64, so I reinstalled the 32bit version, and now it works. So the problem probably was that I had the 64 bit version of Python.

于 2014-03-29T15:22:08.390 回答