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条)

报告相同问题?

悬赏问题

  • ¥20 matlab计算中误差
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊