如何在C代码中使用SWIG生成的C#中的枚举?

时间:2018-03-14 14:04:47

标签: c# c swig

这是我的C enum:

typedef enum {
    VALUE1,
    VALUE2,
    VALUE3
} myenum;

这是我的一个C函数:

myenum getEnumValue1() { 
    return VALUE1; 
}

我期待在C#中得到类似的东西:

public enum SWIGTYPE_p_myenum {
    VALUE1,
    VALUE2,
    VALUE3
}

确实,函数包装器已生成,并返回一个名为myenum的东西,但我没有提到VALUE1等。

如何使用C#包装器?我想做比较,分配,将这些值传递给函数等,但我认为没有办法做到这一点。

例如,我无法执行以下操作:

SWIGTYPE_p_myenum x = SWIGTYPE_p_myenum.VALUE1; 
bool test = (x == SWIGTYPE_p_myenum.VALUE1); 

没有生成的包装代码可以实现这一点。这就是生成的全部内容:

public class SWIGTYPE_p_myenum {
  private global::System.Runtime.InteropServices.HandleRef swigCPtr;

  internal SWIGTYPE_p_myenum(global::System.IntPtr cPtr, bool futureUse) {
    swigCPtr = new global::System.Runtime.InteropServices.HandleRef(this, cPtr);
  }

  protected SWIGTYPE_p_myenum() {
    swigCPtr = new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero);
  }

  internal static global::System.Runtime.InteropServices.HandleRef getCPtr(SWIGTYPE_p_myenum obj) {
    return (obj == null) ? new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero) : obj.swigCPtr;
  }
}

1 个答案:

答案 0 :(得分:1)

来自SWIG docs

  

对于枚举,将原始枚举定义包含在接口文件中的某个位置(在头文件或%{,%}块中)至关重要。 SWIG仅将枚举转换为将常量添加到脚本语言所需的代码。它需要原始的枚举声明来检索正确的枚举值。

确保您正在解析"头文件,以及包括它:

 %module example
 %{
 /* Includes the header in the wrapper code */
 #include "header.h"
 %}

 /* Parse the header file to generate wrappers */

 %include "header.h"  <== don't forget this part