swig转换head中的枚举

2024-10-05 14:24:42 发布

您现在位置:Python中文网/ 问答频道 /正文

在使用SWIG时,我试图从python导入c头文件(我是SWIG的初学者)。头文件中只有宏和枚举。宏可以成功转换,但枚举中出现错误。在

例如,test.h:

typedef enum {
  VAL0,
  VAL1,
  VAL2,
  VAL3
}VALS;

然后呢

^{pr2}$

我成功地得到了一个py函数和一个test_wrap.c文件。奇怪的代码出现了:

SWIG_Python_SetConstant(d, "VAL0",SWIG_From_int((int)(VAL0)));
SWIG_Python_SetConstant(d, "VAL1",SWIG_From_int((int)(VAL1)));
SWIG_Python_SetConstant(d, "VAL2",SWIG_From_int((int)(VAL2)));
SWIG_Python_SetConstant(d, "VAL3",SWIG_From_int((int)(VAL3)));

所以VAL0-3没有定义。然后,当使用以下命令编译时,我得到错误VAL0/VAL1/VAL2/VAL3 unclared:

gcc -c -fpic test_wrap.c -I/usr/lib/python-2.7.5/include/python2.7

我想SWIG注意到这是一个枚举,因为我发现了以下代码:

 static swig_type_info _swigt__p_VALS = {"_p_VALS", "enum VALS *|VALS *", 0, 0, (void*)0, 0};

所以我的问题是为什么它们没有被定义?他们不应该分配为0,1,2,3吗?我该怎么办?在

我在stackoverflow上没有找到类似的问题。如果有其他问题重复,请告诉我。在


Tags: 代码fromtest头文件错误enumswigint
1条回答
网友
1楼 · 发布于 2024-10-05 14:24:42

SWIG documentation on enums上写着:

For enumerations, it is critical that the original enum definition be included somewhere in the interface file (either in a header file or in the %{ %} block). SWIG only translates the enumeration into code needed to add the constants to a scripting language. It needs the original enumeration declaration in order to get the correct enum values as assigned by the C compiler.

由于您使用原始头文件和-module参数调用SWIG,因此您没有遵守该参数。在

幸运的是,解决方法很简单,请添加以下test.i文件:

%module test

%{
#include "test.h"
%}

%include "test.h"

然后打电话给斯威格

^{pr2}$

这将足以使它按预期编译和运行。基本上,所有这些操作只需将#include "test.h"添加到SWIG生成的test_wrap.c文件中。在

相关问题 更多 >