Created
June 17, 2016 17:35
-
-
Save 3d0c/d8583aa8ac8fbc43585620a20a8b9ac9 to your computer and use it in GitHub Desktop.
cgo samples
This file contains 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 <string.h> | |
void write_int(int *len) { | |
*len = 10; | |
} | |
void write_int_array(int *sizes[]) { | |
int stack_sizes[] = {1,2,3}; | |
// Here is an error! | |
// *sizes = stack_sizes; | |
memcpy(sizes, stack_sizes, sizeof(int)*3); | |
} | |
void write_bytes_array(char **data) { | |
char stack_data[] = "asdfg"; | |
// Here is an error! | |
// *data = d; | |
memcpy(data, stack_data, sizeof(char)*strlen(stack_data)); | |
} | |
*/ | |
import "C" | |
import ( | |
"fmt" | |
"unsafe" | |
) | |
func main() { | |
// Right. But type casting will be needed. | |
var cInt C.int | |
C.write_int(&cInt) | |
fmt.Println(cInt) | |
// Wrong. Works, but here we have actually an undefined befavior because of different int types | |
var goInt int | |
C.write_int((*C.int)(unsafe.Pointer(&goInt))) | |
fmt.Println(goInt) | |
// Allocating memory in Go part | |
sizes := make([]C.int, 3) | |
C.write_int_array((**C.int)(unsafe.Pointer(&sizes[0]))) | |
fmt.Println(sizes) | |
// Allocating memory in Go part | |
data := make([]C.char, 5) | |
C.write_bytes_array((**C.char)(unsafe.Pointer(&data[0]))) | |
// Need type casting, output will be bytes array | |
fmt.Println(data) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment