简体   繁体   中英

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. This is main.go file:

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


#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? Because I got this error: panic: runtime error: cgo result has Go pointer

What should I do? Thanks in advance!

Seems like I figure it out myself. change the go function to this:

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

in 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

Correct me if there is any problem

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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