douben1891 2013-09-09 21:08
浏览 46
已采纳

如何从Windows API访问结构中的并集中的变量?

I got input.ki undefined (type C.INPUT has no field or method ki).

I tried using the 'union_' prefix but without any luck.

Any ideas?

package main

// #include <windows.h>
// #include <winuser.h>
import "C"

// http://msdn.microsoft.com/en-us/library/windows/desktop/ms646270(v=vs.85).aspx
// typedef struct tagINPUT {
//   DWORD type;
//   union {
//     MOUSEINPUT    mi;
//     KEYBDINPUT    ki;
//     HARDWAREINPUT hi;
//   };
// } INPUT, *PINPUT;

func main() {
    var input C.INPUT
    var keybdinput C.KEYBDINPUT
    input._type = 1 // ok!
    // input.ki = keybdinput // input.ki undefined (type C.INPUT has no field or method ki)
    // input.union_ki = keybdinput // input.union_ki undefined (type C.INPUT has no field or method union_ki)
}
  • 写回答

2条回答 默认 最新

  • dousi2251 2013-09-10 00:59
    关注

    Because unions break type safety, the only way to access them in Go is with the unsafe package. I think you could do it something like this:

    *(*C.KEYBDINPUT)(unsafe.Pointer(uintptr(unsafe.Pointer(&input)) + unsafe.Sizeof(C.DWORD))) = keybdinput
    

    If I needed to deal with these types much, I would declare wrapper types to make it easier:

    type tagKbdInput struct {
        typ uint32
        ki  C.KEYBDINPUT
    }
    
    type tagMouseInput struct {
        typ uint32
        mi  C.MOUSEINPUT
    }
    
    type tagHardwareInput struct {
        typ uint32
        hi  C.HARDWAREINPUT
    }
    

    Then I could use a simpler conversion through unsafe.Pointer (without pointer arithmetic) to access them:

    (*tagKbdInput)(unsafe.Pointer(&input)).ki = keybdinput
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么