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

How to work with enums in C# generated by SWIG from C code?

这是我的 C 枚举:

typedef enum {
    VALUE1,
    VALUE2,
    VALUE3
} myenum;

这是我的 C 函数之一:

myenum getEnumValue1() { 
    return VALUE1; 
}

我期待在 C# 中得到这样的东西:

public enum SWIGTYPE_p_myenum {
    VALUE1,
    VALUE2,
    VALUE3
}

的确,函数包装器已生成,它 returns 一个名为 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;
  }
}

来自 SWIG docs:

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 to retrieve the correct enum values.

确保你是"parsing"头文件,并包含它:

 %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