英文:
Read a C-type string from Go
问题
我正在尝试用Go编写一个简单的OpenGL应用程序,并希望从驱动程序中读取OpenGL版本。我正在使用这个函数:
http://godoc.org/github.com/chsc/gogl/gl21#GetString
这是一个包装函数,对应的是:
const GLubyte* glGetString(GLenum name);
这段代码:
fmt.Println(gl.GetString(gl.RENDERER))
fmt.Println(*gl.GetString(gl.VERSION))
输出结果为:
0x4708ae0
50
输出结果可能是一个C类型的字符串,指向字符串的第一个字节的指针。我该如何将GetString函数的输出转换为普通的Go字符串?
<br>
<hr>
解决方案:
该包提供了正确的转换函数,只是不太明显:
fmt.Println(gl.GoStringUb(gl.GetString(gl.RENDERER)))
<br>
通用方法:(如果包没有提供*Ubyte到字符串的转换函数)
pointer := unsafe.Pointer(gl.GetString(gl.RENDERER))
str := C.GoString((*C.char)(pointer))
fmt.Println(str)
英文:
I am trying to write a simple OpenGL application in Go and would like to read the OpenGL Version from the driver. I am using this function:
http://godoc.org/github.com/chsc/gogl/gl21#GetString
which is a wrapper function for
const GLubyte* glGetString( GLenum name);
##This code:
fmt.Println(gl.GetString(gl.RENDERER))
fmt.Println(*gl.GetString(gl.VERSION))
outputs
0x4708ae0
50
The output is probably a C-type string, pointer to the first byte of the string. How can I convert the output from the GetString function into a normal go string?
<br>
<hr>
#Solution:
The package provided the right converter function, it is just not really obvious:
fmt.Println( gl.GoStringUb( gl.GetString( gl.RENDERER )))
<br>
###General approach: (if the package wouldn't provide a *Ubyte to string conversion function)
pointer := unsafe.Pointer(gl.GetString(gl.RENDERER))
str := C.GoString( (*C.char)(pointer) )
fmt.Println(str)
答案1
得分: 1
你提供的链接中的包提供了一个名为GoStringUb
的函数,可以完成这个任务:
render := gl.GoStringUb(gl.GetString(gl.RENDERER))
version := gl.GoStringUb(gl.GetString(gl.VERSION))
英文:
The package you linked provides a function GoStringUb
that does the trick:
render := gl.GoStringUb(gl.GetString(gl.RENDERER))
version := gl.GoStringUb(gl.GetString(gl.VERSION))
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论