gpt4 book ai didi

c - 将具有 union 字段的 C 结构映射到 Go 结构

转载 作者:IT王子 更新时间:2023-10-29 01:44:18 32 4
gpt4 key购买 nike

我从 Go 中的某些 WinApi 的系统调用中获取结果。我很容易从 C 代码映射简单的结构,但是如何处理如下所示的 C 结构?

typedef struct SPC_LINK_
{
DWORD dwLinkChoice;
# define SPC_URL_LINK_CHOICE 1
# define SPC_MONIKER_LINK_CHOICE 2
# define SPC_FILE_LINK_CHOICE 3

union
{
LPWSTR pwszUrl;
SPC_SERIALIZED_OBJECT Moniker;
LPWSTR pwszFile;
};

} SPC_LINK, *PSPC_LINK;

如果Go中定义了所有可能的类型

type SPC_LINK struct {
dwLinkChoice DWORD
Moniker SPC_SERIALIZED_OBJECT
pwszFile LPWSTR
pwszUrl LPWSTR
}

在使用 unsafe.Pointer 作为参数的系统调用之后,我将它保存在内存中并且可以像往常一样在 Go 中访问它,但只能访问 之后的第一个字段dwLinkChoice(上面代码中的Moniker)总是填充的,另外两个总是空的。我知道这是 C 中的预期行为,因为您一次只能有一个 union 字段。考虑到这一点,我是否应该忽略整个 union 结构并在我的 Go 结构中使用某种占位符?

type SPC_LINK struct {
dwLinkChoice DWORD
dwLink uintptr // a placeholder, will hold any possible value
}

我将占位符的类型设置为 uintptr,但是如果原始 C 结构在 union block 中有一些其他非指针类型怎么办?我真的不确定如何处理 C union 并寻找任何建议。

最佳答案

cgo documentation 中所述,

As Go doesn't have support for C's union type in the general case, C's union types are represented as a Go byte array with the same length.

也许你应该试试这个

type SPC_LINK struct {
dwLinkChoice DWORD
dwLink [{size of the union}]byte
}

关于c - 将具有 union 字段的 C 结构映射到 Go 结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50432806/

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