如何从C函数返回C结构数组去?

时间:2016-10-12 19:15:17

标签: arrays go struct cgo gccgo

我有一个C函数,它将返回一个结构数组去函数。 我怎样才能收到结构数组并解释或转换为结构?

以下是代码段

&{POST http://localhost:8081/login HTTP/1.1 1 1 map[Region:[San Francisco]] {0xc420553600} 78 [] false localhost:8081 map[] map[] <nil> map[]   <nil> <nil> <nil> <nil>}

我需要在我的go代码中获取pStudent数组

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;
}

有人可以帮我处理代码段吗?

1 个答案:

答案 0 :(得分:0)

您可以使用out参数,以及C struct的方式 - &gt;因此,结构是:

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)
}