Go 错误解决:..go:18:22: cannot convert fmt.Sprintf('%s %s', cmd, cmdArgs) (value of type string) to type []uint16

在 Go 中使用 syscall.CreateProcess 创建子进程时,如果命令行参数 cmdLine 的类型为 []uint16,可能会遇到以下错误:

..go:18:22: cannot convert fmt.Sprintf("%s %s", cmd, cmdArgs) (value of type string) to type []uint16

这是因为 syscall.CreateProcess 函数期望的命令行参数类型为 *uint16,而不是 []uint16

解决办法:

cmdLine 的类型从 []uint16 修改为 *uint16,并将其赋值为 syscall.StringToUTF16Ptr(fmt.Sprintf('%s %s', cmd, cmdArgs)) 即可解决该错误。

修改后的代码:

package main

import (
	"fmt"
	"syscall"
)

func DllMain() {
	// 无用的代码
	for i := 0; i < 100; i++ {
		fmt.Println(i)
	}

	// 创建子进程
	cmd := "cmd"
	cmdArgs := []string{"C", "echo", "hello world"}
	cmdLine := syscall.StringToUTF16Ptr(fmt.Sprintf('%s %s', cmd, cmdArgs))
	startupInfo := &syscall.StartupInfo{}
	processInformation := &syscall.ProcessInformation{}
	err := syscall.CreateProcess(
		nil,
		cmdLine,
		nil,
		nil,
		false,
		0,
		nil,
		nil,
		startupInfo,
		processInformation,
	)
	if err != nil {
		fmt.Println(err)
		return
	}

	// 等待子进程结束并获取返回值
	var exitCode uint32
	syscall.WaitForSingleObject(processInformation.Process, syscall.INFINITE)
	syscall.GetExitCodeProcess(processInformation.Process, &exitCode)

	// 无用的代码
	for i := 0; i < 100; i++ {
		fmt.Println(i)
	}
}

func main() {
	DllMain()
}

// 导出 DllMain 函数
var (
	DllMainPtr = syscall.NewCallback(DllMain)
)

func init() {
	// 将 DllMain 函数注册为 DLL 的入口点
	handle, _ := syscall.LoadLibrary("kernel32.dll")
	defer syscall.FreeLibrary(handle)
	proc, _ := syscall.GetProcAddress(handle, "DllMain")
	syscall.Syscall(proc, 0, 0, 1, uintptr(unsafe.Pointer(&DllMainPtr)))
}

解释:

  • syscall.StringToUTF16Ptr 函数将 UTF-8 字符串转换为 UTF-16 编码的 *uint16 指针,并返回该指针。
  • syscall.CreateProcess 函数的第二个参数 CommandLine 接受 *uint16 类型的指针,用于指定要执行的命令行参数。

通过以上修改,可以成功解决 “cannot convert fmt.Sprintf('%s %s', cmd, cmdArgs) (value of type string) to type []uint16” 错误。

注意:

在使用 syscall.StringToUTF16Ptr 函数时,需要确保传入的字符串为 UTF-8 编码。否则,可能会导致程序出现异常。

希望本文能够帮助你解决这个问题。如果你有任何疑问或建议,请随时评论或联系我。

Go 错误解决:..go:18:22: cannot convert fmt.Sprintf(

原文地址: https://www.cveoy.top/t/topic/lMQ7 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录