Skip to content

Instantly share code, notes, and snippets.

@3lbios
Created January 30, 2020 00:39
Show Gist options
  • Save 3lbios/0f5ece1e4a9563650ff70ce54c1fde28 to your computer and use it in GitHub Desktop.
Save 3lbios/0f5ece1e4a9563650ff70ce54c1fde28 to your computer and use it in GitHub Desktop.
Example Go to C communication (cgo FFI)
go build -buildmode=c-archive c_ffi.go &&
gcc -pedantic -Wall -Wextra main.c c_ffi.a -lpthread -o test.elf
./test.elf
output:
x, x, x, x, x, x, x, x, x, x, x, x, x, x, x, x, x, x, x, x, x, x, x, x, x, x, x, x, x, x, x, x, x, x, x, x, x, x, x, x, x, x, x, x, x, x, x, x, x, x, x, x, x, x, x, x, x, x, x, x, x, x, x, x, x, x, x, x, x, x, x, x, x, x, x, x, x, x, x, x, x, x, x, x, x, x, x, x, x, x, x, x, x, x, x, x, x, x, x, x,
package main
import (
"C"
"unsafe"
)
//export fill_c_array_from_go
func fill_c_array_from_go(data unsafe.Pointer, sz int) {
for i := 0; i < sz; i++ {
p := unsafe.Pointer(uintptr(data) + uintptr(i))
ptr := (*uint8)(p)
*ptr = 'x'
}
}
func main() {
// Deliberately empty.
}
#include "c_ffi.h" //generated by 'go build'
#include <stdio.h>
#include <string.h>
#include <unistd.h>
int main(void)
{
char data[100];
int i;
memset(data, 0, 100);
//this call triggers startup of Go runtime
fill_c_array_from_go(data, 100);
for (i = 0; i < 100; ++i)
printf("%c, ", data[i]);
printf("\n");
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment