简体   繁体   English

使用swig解析头文件

[英]Parsing a header file using swig

I have a header file with struct definitions that I'd like to be able to parse in python. 我有一个带有结构定义的头文件,我希望能够在python中进行解析。 In order to do this I turned to Swig. 为了做到这一点,我转向了Swig。

Lets say the header file is named "ah". 可以说头文件被命名为“ ah”。 I first renamed it to "ac" and added an empty "ah" file in the same folder. 我首先将其重命名为“ ac”,然后在同一文件夹中添加了一个空的“ ah”文件。

Next, I added in an "a_wrap.i" file with the following contents. 接下来,我添加了具有以下内容的“ a_wrap.i”文件。

%module a
%{
    /* the resulting C file should be built as a python extension */
    #define SWIG_FILE_WITH_INIT
    /*  Includes the header in the wrapper code */
    #include "a.h"
%}
/*  Parse the header file to generate wrappers */
%include "a.h"
extern struct a_a;
extern struct a_b;
extern struct a_c;

Next, I wrote a setup.py file as follows : 接下来,我编写了一个setup.py文件,如下所示:

from distutils.core import setup, Extension

setup(ext_modules=[Extension("_a",
      sources=["a.c", "a_wrap.i"])])

Next, I did the build as 接下来,我按照

python setup.py build_ext --inplace 

I finally tried to import it in python 我终于尝试将其导入python

>>> import a # it works, yaay
>>> dir(a)
...
...

I was hoping for a way to access the structs defined in "ac"(originally ah). 我希望找到一种方法来访问“ ac”(最初是ah)中定义的结构。 However, I don't seem to be able to find a way to do that. 但是,我似乎找不到能够做到这一点的方法。 How can I solve this? 我该如何解决? I'm looking for a way to access the struct's defined in the header file from python. 我正在寻找一种从python访问头文件中定义的结构的方法。

The global variables a_a , a_b and a_c should be accessible from [within your SWIG Python module via cvar`] 1 : 全局变量a_aa_b and a_c should be accessible from [within your SWIG Python module via cvar` should be accessible from [within your SWIG Python module via内] 1访问

import a
print a.cvar.a_a
print a.cvar.a_b
# etc.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM