繁体   English   中英

如何将 Go 中的 []byte 切片返回到 C

[英]How to return a []byte slice in Go to C

我正在尝试编写一个返回字节 [] 的 go function 并在 C 中使用它。 这是 main.go 文件:

package main

import "C"
import (
    "unsafe"
)

//export hello
func hello() *C.char { 

    
    buff := []byte{1, 2, 3}
    res := unsafe.Pointer(&buff)
    result := (*C.char)(res)
    return result
}
func main() {

}

这是 C 文件:test.c


#include <stdio.h>
#include <string.h>
#include "hello.h"                       

int main(){
       
        char *c = hello();
        printf("r:%s",c);
}

但似乎我返回的仍然是 Go 指针? 因为我收到了这个错误:恐慌:运行时错误:cgo 结果有 Go 指针

我应该怎么办? 提前致谢!

好像是我自己想出来的。 将 go function 更改为:

//export hello
func hello() *C.char { // 如果函数有返回值,则要将返回值转换为C语言对应的类型
    buff := []byte{1, 2, 3}
    res := C.CBytes(buff)
    result := (*C.char)(res)
    return result
}

在 C 中:

int main(){
        int i;
        char *c = hello();
        for ( i = 0; i < 3; i++ )
           {
               printf( "*(c + %d) : %d\n", i, *(c + i));
           }

}

output:

*(c + 0) : 1
*(c + 1) : 2
*(c + 2) : 3

如果有任何问题请纠正我

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM