跨互操作边界使用枚举是否安全?

Is it safe to use enums across interop boundaries?

我正在编写一组 DLL,它允许其他开发人员编写他们自己的 DLL 作为扩展。在 Delphi 代码中,我广泛使用枚举和枚举集。我通过 DLL 使用枚举。我知道我可以在使用 Delphi 编译的不同项目中通过 DLL 安全地使用枚举。但是,我不确定它对各种语言的适应性如何。

在支持其他各种语言的同时通过 DLL 使用枚举是否安全?或者我应该将其转换为整数?

枚举需要作为整数(Word 或 DWORD)传递,您应该使用编译器指令 {$MINENUMSIZE}(也称为 {$Z})以确保它们的大小正确。 Delphi 编译器将根据枚举值的数量使用不同的大小,除非您这样做。

如果您计划与 Windows OS 上的 C/C++ 代码互操作,请使用 {$MINENUMSIZE 4}.

我上面链接的文档解决了与 C/C++ 的互操作问题 - 请参阅第三段:

The $Z directive controls the minimum storage size of Delphi enumerated types.

An enumerated type is stored as an unsigned byte if the enumeration has no more than 256 values, and if the type was declared in the {$Z1} state (the default). If an enumerated type has more than 256 values, or if the type was declared in the {$Z2} state, it is stored as an unsigned word. Finally, if an enumerated type is declared in the {$Z4} state, it is stored as an unsigned double word.

The {$Z2} and {$Z4} states are useful for interfacing with C and C++ libraries, which usually represent enumerated types as words or double words.