gpt4 book ai didi

python - C : What assumptions can be made about the value of the underlying variable? 中的枚举

转载 作者:太空宇宙 更新时间:2023-11-04 00:37:36 24 4
gpt4 key购买 nike

我正在编写一些通过 python 的 ctypes 模块调用 C dll 的 python 代码。

有问题的 DLL 在其头文件中将一些返回值定义为 enum:

//
// Device status
//
enum {
FT_OK,
FT_INVALID_HANDLE,
FT_DEVICE_NOT_FOUND,
FT_DEVICE_NOT_OPENED,
FT_IO_ERROR,
FT_INSUFFICIENT_RESOURCES,
FT_INVALID_PARAMETER,
<continued---snip>
};

我是从 python 接口(interface)的,所以我没有 native 枚举。我可以假设枚举的内容从 0 的值开始,并为每个项目递增 1 吗?这很容易实现,但似乎我会依赖编译器的实现细节。

我已经对 enum 变量的内部结构进行了一些挖掘,但我找不到太多关于它们在内部如何工作的信息。只有关于如何在 C/C# 中使用它们的文档。

我知道 enum 是否有各种变量的常量定义,我可以依赖它,但在这种情况下,我正在与我无权访问的外部代码交互(只是 dll)。

最佳答案

draft C99 standard6.7.2.2 Enumeration specifiers3 中说:

If the first enumerator has no =, the value of its enumeration constant is 0. Each subsequent enumerator with no = defines its enumeration constant as the value of the constant expression obtained by adding 1 to the value of the previous enumeration constant. (The use of enumerators with = may produce enumeration constants with values that duplicate other values in the same enumeration.) The enumerators of an enumeration are also known as its members.

它还提供了一个例子来阐明:

enum hue { chartreuse, burgundy, claret=20, winedark };

并说:

The enumerated values are in the set { 0, 1, 20, 21 }.

不清楚您是否关心底层类型,但 4 段说:

Each enumerated type shall be compatible with char, a signed integer type, or an unsigned integer type. The choice of type is implementation-defined,110) but shall be capable of representing the values of all the members of the enumeration. The enumerated type is incomplete until after the } that terminates the list of enumerator declarations.

关于python - C : What assumptions can be made about the value of the underlying variable? 中的枚举,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24946699/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com