dsfovbm931034814 2016-10-12 19:15
浏览 137

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

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?

  • 写回答

1条回答 默认 最新

  • dsfgds4215 2016-10-13 07:15
    关注

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

报告相同问题?

悬赏问题

  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作