将字节数组从Go传递到CGO

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

passing a byte array from go to cgo

问题

我有以下的C代码:

uint32_t cHash32(const char *s, size_t len) { return util::Hash32(s, len); }

我正在一个Go项目中这样调用它:

func Hash32(s []byte) uint32 {
    return uint32(C.cHash32((*C.char)(unsafe.Pointer(&s[0])), C.size_t(len(s))))
}

不知何故,结果出错了。

当传入"hi"时,根据同一库的Python绑定(Google的farmhash),预期结果应该是4063302914。

我猜想假设s可以转换为*C.char有点天真,不是吗!

我该如何将s的内容作为*C.char传递?

英文:

I have the following C code

uint32_t cHash32(const char *s, size_t len) { return util::Hash32(s, len); }

I am calling it from a go project as follows

func Hash32(s []byte) uint32 {
	return uint32(C.cHash32((*C.char)(unsafe.Pointer(&s)),   C.size_t(len(s))))
}

Somehow the result is broken.

When passing "hi" the expected result should be 4063302914 according to the python bindings to the same library (farmhash by google).

I guess that assuming s can be translated to a *C.char is a bit naive isn't it!

How do I pass the content of s as a *C.char?

答案1

得分: 3

是的,你可以通过在Go语言中使用C.CString来创建*C.char。在Google Playground上不允许使用cgo,所以你需要下载这个链接并在本地运行它才能使用。

http://play.golang.org/p/inthA1i0C2

将字节切片转换为字符串,然后再转换为*char C.CString(string([]byte("bytes")))

英文:

Yes, you can create *C.char in Go via C.CString. cgo is not allowed on google playground, so you will need to download this link and run it locally to use it.

http://play.golang.org/p/inthA1i0C2

Convert the byte slice to a string, then to *char C.CString(string([]byte("bytes"))).

huangapple
  • 本文由 发表于 2015年7月11日 20:56:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/31357414.html
匿名

发表评论

匿名网友

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

确定