Created
October 20, 2022 18:47
-
-
Save alexcoder04/f0d6360a086a1a665fff8710298731b9 to your computer and use it in GitHub Desktop.
CGO example
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 "greet.h" | |
#include <stdio.h> | |
int greet(const char *name, char *out) { | |
int n; | |
n = sprintf(out, "Hello %s!", name); | |
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, 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 "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)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is an example how to use CGo (import C code from Go)