登录
首页 >  Golang >  Go问答

在 Go 中加载 Windows DLL?

来源:stackoverflow

时间:2024-04-18 14:00:38 321浏览 收藏

积累知识,胜过积蓄金银!毕竟在Golang开发的过程中,会遇到各种各样的问题,往往都是一些细节知识点还没有掌握好而导致的,因此基础知识点的积累是很重要的。下面本文《在 Go 中加载 Windows DLL?》,就带大家讲解一下知识点,若是你对本文感兴趣,或者是想搞懂其中某个知识点,就请你继续往下看吧~

问题内容

我需要在我的应用程序中使用 Windows DLL,特别是 kernel32.dll。 我只找到这个:WindowsDLL

但是这个“指南”并不那么直观。

例如,在 Python 中您使用 ctypes。 ej: ctypes.windll.kernel32.SetConsoleTextAtribute(句柄, 颜色)

我怎样才能在 Golang 中做出同样的事情?

任何人都可以举一些我想要的例子吗?


解决方案


实际上,您提供的链接是一个很好的参考。 您现在所需要做的就是选择建议的实现之一。

您可以在此处找到 kernel32.setconsoletextatribute 的文档:https://learn.microsoft.com/en-us/windows/console/setconsoletextattribute

公开的 api 定义为:

bool winapi setconsoletextattribute(
  _in_ handle hconsoleoutput,
  _in_ word   wattributes
);

第二个选项的示例(使用 syscall.newproc):

package main

import (
    "os"
    "syscall"
)

const (
    // defined base colors
    ForegroundBlue      uint = 1
    ForegroundGreen     uint = 2
    ForegroundRed       uint = 4
    ForegroundIntensity uint = 8
    BackgroundBlue      uint = 16
    BackgroundGreen     uint = 32
    BackgroundRed       uint = 64
    BackgroundIntensity uint = 128

    // colors can also be mixed
    ForegroundGrey = ForegroundBlue | ForegroundGreen | ForegroundRed
    ForegroundWhite = ForegroundBlue | ForegroundGreen | ForegroundRed | ForegroundIntensity
)

func main() {
    kernel32 := syscall.NewLazyDLL("kernel32.dll")
    setConsoleTextAttribute := kernel32.NewProc("SetConsoleTextAttribute")
    stdOutHandle := os.Stdout.Fd()

    attributes := ForegroundWhite | BackgroundRed
    ret, _, err := setConsoleTextAttribute.Call(stdOutHandle, uintptr(attributes))
    if err != nil {
        panic(err) // calling kernel32.SetConsoleTextAttribute failed
    }

    if ret == 0 {
        print("Could not set the desired attributes")
        // TODO: call GetLastError to get more information
    }

    print("OK")
}

文中关于的知识介绍,希望对你的学习有所帮助!若是受益匪浅,那就动动鼠标收藏这篇《在 Go 中加载 Windows DLL?》文章吧,也可关注golang学习网公众号了解相关技术文章。

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>