将具有并集字段的C结构映射到Go结构 [英] Map C struct with union field to Go struct

查看:49
本文介绍了将具有并集字段的C结构映射到Go结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从syscall到Go中的某些WinApi取得结果.我可以轻松地从C代码映射简单的结构,但是如何处理如下的C结构呢?

I'm getting results from syscall to some WinApi in Go. I map simple structs from C code easily, but how to deal with C structs like the following?

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中定义了所有可能的类型

If all possible types are defined in Go

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

在系统调用后,以 unsafe.Pointer 作为该Go结构的

参数,我已经将它存储在内存中,并且可以像往常一样在Go中访问它,但是只有之后的第一个字段dwLinkChoice (上面代码中的 Moniker )始终填充,其他两个始终为空.我知道这是C语言中的预期行为,因为一次只能有一个联合字段.考虑到这一点,我是否应该忽略整个联合结构,并在Go结构中使用某种占位符?

after the syscall with unsafe.Pointer to this Go struct as a parameter, I've got it in memory and can access it in Go as usual, but only the first field after dwLinkChoice (Moniker in the code above) is always filled, the other two are always empty. I know this is expected behavior in C, as you can have only one union field at a time. Taking this into account, should I ignore the whole union structure and have some sort of a placeholder in my Go struct?

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

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

I set type for the placeholder to uintptr, but what if the original C structure has some other non-pointer types in the union block? I'm really not sure how to handle C unions and looking for any suggestions.

推荐答案

cgo文档中所述

由于Go通常不支持C的联合类型,因此C的联合类型表示为具有相同长度的Go字节数组.

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结构映射到Go结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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