dounianluo0086 2016-10-24 07:32
浏览 138
已采纳

如何从C函数将字符串读取到Go中?

I'm trying to call a C function from Go with cgo to read an error message. The function produces a message of an unknown length less than 256 bytes.

Working example in C:

char message[ERROR_SIZE]; //256
last_error( message, sizeof(message) );         
printf( "message: %s
", message );

My attempt in Go (not working):

var ptr *C.char
C.last_error(ptr, ERROR_SIZE)
var message = C.GoString(ptr)
fmt.Printf("message: %s
", message)

When the go code is run, the message is empty. Does the go version need to preallocate space for the message? How to do this?


Update after comment by LPs to pass an array. This works, but seems a bit awkward:

var buf [ERROR_SIZE]byte
var ptr = (*C.char)(unsafe.Pointer(&buf[0]))
C.last_error(ptr, len(buf))
var message = C.GoString(ptr)
fmt.Printf("message: %s
", message)

Is there a simpler way?

  • 写回答

1条回答 默认 最新

  • douchun6221 2016-10-24 14:31
    关注

    In your first example you are passing a nil pointer, so there is no allocated memory for C.last_error to write the output to (and luckily, it appears to just do nothing).

    You need to allocate the memory somehow, and the most straightforward way to do that in Go is to use a slice, rather than create an array with a static size.

    buf := make([]byte, ERROR_SIZE)
    C.last_error((*C.char)(unsafe.Pointer(&buf[0])), len(buf))
    
    // While C.GoString will find the terminating null if it's there, 
    // there's no reason to copy the string in C, and allocate another slice.
    if i := bytes.IndexByte(buf, 0); i >= 0 {
        buf = buf[:i]
    }
    
    fmt.Printf("message: %s
    ", buf)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 基于单片机的靶位控制系统
  • ¥15 AT89C51控制8位八段数码管显示时钟。
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错