Skip to content

Instantly share code, notes, and snippets.

@obscuren
Created January 10, 2015 00:54
Show Gist options
  • Save obscuren/b785d69886fdcc077d13 to your computer and use it in GitHub Desktop.
Save obscuren/b785d69886fdcc077d13 to your computer and use it in GitHub Desktop.
CGO return VM data
package main
//#include <stdio.h>
//#include <strings.h>
//#include <stdlib.h>
/*
typedef struct {
unsigned char *data;
int data_len;
} Result;
Result *foo() {
Result *r = malloc(sizeof(Result));
r->data = (unsigned char *)malloc(10);
r->data_len = 10;
memset(r->data, 0, 10);
r->data = (unsigned char *)strdup("xxx123");
r->data_len = 6;
return r;
}
*/
import "C"
import (
"fmt"
"unsafe"
)
func main() {
result := C.foo()
str := (*C.char)(unsafe.Pointer(result.data))
fmt.Println("As string:", C.GoString(str))
byts := C.GoBytes(unsafe.Pointer(result.data), result.data_len)
fmt.Println("As bytes:", byts)
// Free r->data
C.free(unsafe.Pointer(result.data))
// Free Result *r
C.free(unsafe.Pointer(result))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment