跨互操作边界使用枚举是否安全? [英] Is it safe to use enums across interop boundaries?

查看:74
本文介绍了跨互操作边界使用枚举是否安全?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm writing a set of DLLs which allows other developers write their own DLL as an extension. In the Delphi code, I widely use enums, and enum sets. I use enums through DLLs. I know I can safely use an enum through a DLL across different projects compiled with Delphi. However, I'm not sure about how adaptable it is across various languages.

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

Is it safe to use enums through a DLL while supporting other various languages? Or should I cast it as an integer instead?

推荐答案

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

Enums need to be passed as integers (Word or DWORD), and you should use the compiler directive {$MINENUMSIZE} (AKA {$Z}) to ensure that they're the proper size. The Delphi compiler will use different sizes based on the number of enum values unless you do so.

如果您打算在Windows OS上与C / C ++代码互操作,请使用 {$ MINENUMSIZE 4}

If you're planning to interop with C/C++ code on the Windows OS, use {$MINENUMSIZE 4}.

我上面链接的文档涉及与C / C ++的互操作-参见第三段:

The documentation I linked above addresses interop with C/C++ - see the third paragraph:


$ Z指令控制Delphi枚举类型的最小存储大小。

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

如果枚举,枚举类型将存储为无符号字节。最多包含256个值,并且类型是在{$ Z1}状态(默认)中声明的。如果枚举类型具有超过256个值,或者如果该类型以{$ Z2}状态声明,则将其存储为无符号字。最后,如果枚举类型在{$ Z4}状态中声明,则将其存储为无符号双字。

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.

{$ Z2}和{$ Z4}状态对于与C和C ++库接口,C和C ++库通常将枚举类型表示为单词或双字。

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

这篇关于跨互操作边界使用枚举是否安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆