英文:
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 <windows.h>
import "C"
import "unsafe"
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 <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))
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论