Created
June 6, 2019 16:01
-
-
Save mattheusv/5d734379ecce28b6ebe10a068d4304c4 to your computer and use it in GitHub Desktop.
C to Go
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
#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; | |
} |
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
#ifndef _GREETER_H | |
#define _GREETER_H | |
int greet(const char *name, int year, char *out); | |
#endif |
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 | |
// #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