Skip to content

Instantly share code, notes, and snippets.

@jmptrader
Forked from 3d0c/cgo-sample.go
Created January 10, 2017 13:02
Show Gist options
  • Save jmptrader/758b103848e04c709af042696846925c to your computer and use it in GitHub Desktop.
Save jmptrader/758b103848e04c709af042696846925c to your computer and use it in GitHub Desktop.
cgo samples
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