Skip to content

Instantly share code, notes, and snippets.

@mattheusv
Created June 6, 2019 16:01
Show Gist options
  • Save mattheusv/5d734379ecce28b6ebe10a068d4304c4 to your computer and use it in GitHub Desktop.
Save mattheusv/5d734379ecce28b6ebe10a068d4304c4 to your computer and use it in GitHub Desktop.
C to Go
#include "greeter.h"
#include <stdio.h>
int greet(const char *name, int year, char *out) {
int n;
n = sprintf(out, "Greetings, %s from %d! We come in peace :)", name, year);
return n;
}
#ifndef _GREETER_H
#define _GREETER_H
int greet(const char *name, int year, char *out);
#endif
package main
// #cgo CFLAGS: -g -Wall
// #include <stdlib.h>
// #include "greeter.h"
import "C"
import (
"fmt"
"unsafe"
)
func main() {
name := C.CString("Gopher")
defer C.free(unsafe.Pointer(name))
year := C.int(2018)
ptr := C.malloc(C.sizeof_char * 1024)
defer C.free(unsafe.Pointer(ptr))
size := C.greet(name, year, (*C.char)(ptr))
b := C.GoBytes(ptr, size)
fmt.Println(string(b))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment