0

我有一个 C 函数,它将返回一个结构数组来运行函数。如何接收结构数组并解释或转换为结构?

这是代码片段

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

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

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() //?????


}

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

4

1 回答 1

1

您可以使用 out 参数,因此 C struct -> Go struct 的方式是:

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)
}
于 2016-10-13T07:15:44.667 回答