Created
January 10, 2015 00:54
-
-
Save obscuren/b785d69886fdcc077d13 to your computer and use it in GitHub Desktop.
CGO return VM data
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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