cgo 结果有 go 指针

标签 c go cgo

我正在编写一些导出这样的函数的代码:

package main
import "C"

//export returnString
func returnString() string {
    //
    gostring := "hello world"
    return gostring
}
func main() {}

我使用 go build -buildmode=c-shared 构建了 .so 和头文件,但是当我调用 returnString() 在我的 C 代码中,我得到 panic: runtime error: cgo result has Go pointer

在 go 1.9 中有办法做到这一点吗?

最佳答案

您需要将您的 go 字符串转换为 *C.charC.Cstring 是它的实用函数。

package main

import "C"

//export returnString
func returnString() *C.char {
    gostring := "hello world"
    return C.CString(gostring)
}

func main() {}

关于cgo 结果有 go 指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48686763/

相关文章:

c - 为什么我可以进入 alloca :d variable, 的范围而不是可变长度数组?

使用 RS232 的 C 程序仅在启动 minicom 时有效

c# - 通过 C# 对 C 程序的多个输入

c - 在 Go 程序中使用 C 代码时未声明的标识符

c - 是否需要 C.GoBytes 来检索 C 缓冲区,或者这里的指针是否足够?

Go不能调用c++函数

c - Emacs semantic+auto-complete-mode for C

mysql - MySQL返回 “Too many connections”错误

go - 如何为 gRPC 服务器提供请求根上下文?

go - 如何通过 golang 中的 CGO 将 Go 字符串复制到 C char *?