Reputation: 69
I have a C function which will return an array of structure to go function. How can I receive the array of structure and interpret or cast to go structure?
Here is the code snippet
typedef struct student{
nameStruct name;
addressStruct address;
} studentStruct;
typedef struct name{
char firstName[20];
char lastName[20];
} nameStruct;
typedef struct address{
char location[40];
int pin;
}addressStruct;
student* getAllStudents(){
//Allocate memory for N number of students
student *pStudent= (struct student*)(N* sizeof(struct student));
//populate the array
return pStudent;
}
I need to get the pStudent array in my go code
package main
/*
#cgo CFLAGS: -I.
#cgo LDFLAGS: -L. -lkeyboard
#include "keyboard.h"
*/
import "C"
import (
"fmt"
)
type student struct {
name string
ID int
}
func main() {
s := student{} //Need to know how to decide the length of the struct array
s = C.getAllStudents() //?????
}
Can some one help me with code snippet?
Upvotes: 0
Views: 2049
Reputation: 101
You could use the out paramters, and the way for C struct -> Go struct is thus:
package main
/*
#include <stdlib.h>
typedef struct Point{
float x;
float y;
}Point;
void GetPoint(void **ppPoint) {
Point *pPoint= (Point *)malloc(sizeof(Point));
pPoint->x=0.5f;
pPoint->y=1.5f;
*ppPoint = pPoint;
}
*/
import "C"
import "unsafe"
type Point struct {
x float32
y float32
}
func main() {
var ppoint unsafe.Pointer
C.GetPoint(&ppoint)
point := *(*Point)(ppoint)
println(point.x, point.y)
}
Upvotes: 1