Skip to content

Instantly share code, notes, and snippets.

@alexcoder04
Created October 20, 2022 18:47
Show Gist options
  • Save alexcoder04/f0d6360a086a1a665fff8710298731b9 to your computer and use it in GitHub Desktop.
Save alexcoder04/f0d6360a086a1a665fff8710298731b9 to your computer and use it in GitHub Desktop.
CGO example
#include "greet.h"
#include <stdio.h>
int greet(const char *name, char *out) {
int n;
n = sprintf(out, "Hello %s!", name);
return n;
}
#ifndef _GREETER_H
#define _GREETER_H
int greet(const char *name, char *out);
#endif
package main
// #cgo CFLAGS: -g -Wall
// #include <stdlib.h>
// #include "greet.h"
import "C"
import (
"bufio"
"fmt"
"os"
"strings"
"unsafe"
)
// help function, unrelated to cgo
func Input(prompt string) (string, error) {
fmt.Print(prompt)
r := bufio.NewReader(os.Stdin)
return r.ReadString('\n')
}
func main() {
// do some go code (enter name)
input, err := Input("Enter your name: ")
if err != nil {
return
}
// c variable for name
name := C.CString(strings.TrimSpace(input))
defer C.free(unsafe.Pointer(name))
// c pointer for the result
ptr := C.malloc(C.sizeof_char * 1024)
defer C.free(unsafe.Pointer(ptr))
// execute c code
size := C.greet(name, (*C.char)(ptr))
// get bytes from pointer into go variable
b := C.GoBytes(ptr, size)
// do some go code again
fmt.Println(string(b))
}
@alexcoder04
Copy link
Author

This is an example how to use CGo (import C code from Go)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment