从Go中读取一个C类型的字符串。

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

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))

huangapple
  • 本文由 发表于 2014年1月27日 06:56:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/21370390.html
匿名

发表评论

匿名网友

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

确定