Created
January 30, 2020 00:39
-
-
Save 3lbios/0f5ece1e4a9563650ff70ce54c1fde28 to your computer and use it in GitHub Desktop.
Example Go to C communication (cgo FFI)
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
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, |
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 | |
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. | |
} |
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 "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