Skip to content

Instantly share code, notes, and snippets.

@akamensky
Last active March 27, 2018 18:01
Show Gist options
  • Save akamensky/94de5ea0f912668a419583abe5918bce to your computer and use it in GitHub Desktop.
Save akamensky/94de5ea0f912668a419583abe5918bce to your computer and use it in GitHub Desktop.
Passing arrays of structs between Go and C
  1. Put cinterface.go, cinterface.c and test.h in ~/go/src/cinterface/
  2. Then call go build -buildmode=c-archive cinterface, this will produce cinterface.a and cinterface.h in current directory
  3. Put main.c and test.h in current directory and call gcc -o main -I. cinterface.a main.c, this will produce final binary
#include <stdlib.h>
#include "test.h"
struct example * getArray(int size) {
struct example *result = malloc(sizeof(struct example)*size);
return result;
}
void putData(struct example * array, int position, unsigned long long number, char *str) {
struct example *element = &array[position];
element->number = number;
element->str = str;
}
package main
/*
#include <stdlib.h>
#include "test.h"
*/
import "C"
type testing struct {
number uint64
str string
}
var data = []testing{
{number:1, str:"one"},
{number:2, str:"two"},
{number:3, str:"three"},
}
var ptr *C.struct_example
var ptrSize C.int
func main() {
// do nothing
}
//export Prepare
func Prepare() {
ptrSize = C.int(len(data))
ptr = C.getArray(ptrSize)
for i:=0; i<len(data);i++ {
C.putData(ptr,C.int(i), C.ulonglong(data[i].number), C.CString(data[i].str))
}
}
//export GoGetArray
func GoGetArray() *C.struct_example {
return ptr
}
//export GoGetArrayLength
func GoGetArrayLength() C.int {
return ptrSize
}
#include <stdio.h>
#include "cinterface.h"
int main() {
Prepare();
struct example *ptr = (struct example *)GoGetArray();
int ptr_size = GoGetArrayLength();
printf("Number of elements: %d\n", ptr_size);
for(int i = 0; i < ptr_size; i++) {
struct example e = ptr[i];
printf("Element %d: number=%llu, str=%s\n", i, e.number, e.str);
}
return 0;
}
struct example
{
unsigned long long number;
char *str;
};
struct example * getArray(int size);
void putData(struct example * array, int position, unsigned long long number, char *str);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment