简体   繁体   English

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

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

I am trying to write a go function that returns a byte[] and use it in C.我正在尝试编写一个返回字节 [] 的 go function 并在 C 中使用它。 This is main.go file:这是 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() {

}

and Here is the C file: test.c这是 C 文件:test.c


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

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

But seems like what I return is still a Go pointer?但似乎我返回的仍然是 Go 指针? Because I got this error: panic: runtime error: cgo result has Go pointer因为我收到了这个错误:恐慌:运行时错误:cgo 结果有 Go 指针

What should I do?我应该怎么办? Thanks in advance!提前致谢!

Seems like I figure it out myself.好像是我自己想出来的。 change the go function to this:将 go function 更改为:

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

in C:在 C 中:

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

}

output: output:

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

Correct me if there is any problem如果有任何问题请纠正我

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

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