Golang CGO 无法使用转换后的字符串。

huangapple go评论81阅读模式
英文:

Golang CGO unable to use converted string

问题

我正在尝试使用CGO和Windows C头文件来设置Windows命令提示符的标题:

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

func Title(title string) {
  ctitle := C.CString(title)
  defer C.free(unsafe.Pointer(ctitle))
  C.SetConsoleTitle(ctitle)
}

但在编译时,出现以下错误:

cannot use ctitle (type *C.char) as type *C.CHAR in argument to _Cfunc_SetConsoleTitle

似乎C.SetConsoleTitle(ctitle)期望的是*C.CHAR类型的字符串,但C.CString(title)返回的是*C.char类型。

你应该如何将字符串转换为期望的类型?

英文:

I'm attempting to set the title of the Windows command prompt using CGO and the windows c header:

// #include &lt;windows.h&gt;
import &quot;C&quot;
import &quot;unsafe&quot;

func Title(title string) {
  ctitle := C.CString(title)
  defer C.free(unsafe.Pointer(ctitle))
  C.SetConsoleTitle(ctitle)
}

But at compile time, the following error occurs:

cannot use ctitle (type *C.char) as type *C.CHAR in argument to _Cfunc_SetConsoleTitle

It would seem that C.SetConsoleTitle(ctitle) is expecting a string of type *C.CHAR but C.CString(title) is returning *C.char

How should I go about converting the string to the expected type?

答案1

得分: 1

我找到了一个解决方案,你可以将指针转换为*C.CHAR

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

func Title(title string) {
  ctitle := unsafe.Pointer(C.CString(title))
  defer C.free(ctitle)
  C.SetConsoleTitle((*C.CHAR)(ctitle))
}

这段代码可以将字符串转换为C语言的字符串,并将其传递给SetConsoleTitle函数来设置控制台窗口的标题。

英文:

I've found a solution, You're able to cast the pointer to an *C.CHAR:

// #include &lt;windows.h&gt;
import &quot;C&quot;
import &quot;unsafe&quot;

func Title(title string) {
  ctitle := unsafe.Pointer(C.CString(title))
  defer C.free(ctitle)
  C.SetConsoleTitle((*C.CHAR)(ctitle))
}

huangapple
  • 本文由 发表于 2016年1月22日 14:31:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/34940385.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定