doubengman2072 2019-01-09 04:22
浏览 114

如何在cgo中访问全局变量?

The memory of the structure is already allocated.

I would like to approach C struct in golang.

I want to access a struct variable in golang without the c code, what should I do?

package main

/*
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct 
{
        int   num;
        char  food[10];
        char  animal[128];
} sample;

sample *sa;

static void alloc() {
        sa = (sample *) malloc (sizeof(sample) * 2);
        memset(sa, 0, sizeof(sample) * 2);

        sa[0].num = 10;
        strcpy(sa[0].food, "noodle");
        strcpy(sa[0].animal, "cat");

    sa[1].num = 20;
    strcpy(sa[1].food, "pizza");
    strcpy(sa[1].animal, "dog");
}

*/
import "C"

import "fmt"

func init() {
        C.alloc()
}
func main() {
        fmt.Println(C.sa[0].num)
        fmt.Println(C.sa[0].food)
        fmt.Println(C.sa[0].animal)

        fmt.Println(C.sa[1].num)
        fmt.Println(C.sa[1].food)
        fmt.Println(C.sa[1].animal)
}

I have written this example.

  • 写回答

1条回答 默认 最新

  • drh37116 2019-01-09 06:10
    关注

    For example,

    sample.go:

    package main
    
    /*
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    typedef struct
    {
        int   num;
        char  food[10];
        char  animal[128];
    } sample;
    
    sample *sa = NULL;
    int sn = 0;
    
    static void alloc() {
        sn = 2;
        sa = (sample *) malloc (sizeof(sample) * sn);
        memset(sa, 0, sizeof(sample) * sn);
    
        sa[0].num = 10;
        strcpy(sa[0].food, "noodle");
        strcpy(sa[0].animal, "cat");
    
        sa[1].num = 20;
        strcpy(sa[1].food, "pizza");
        strcpy(sa[1].animal, "dog");
    }
    */
    import "C"
    
    import (
        "fmt"
        "unsafe"
    )
    
    var sa []C.sample
    
    func init() {
        C.alloc()
        sa = (*[1 << 30 / unsafe.Sizeof(C.sample{})]C.sample)(unsafe.Pointer(C.sa))[:C.sn:C.sn]
    }
    
    func CToGoString(c []C.char) string {
        n := -1
        for i, b := range c {
            if b == 0 {
                break
            }
            n = i
        }
        return string((*(*[]byte)(unsafe.Pointer(&c)))[:n+1])
    }
    
    func main() {
        for i := range sa {
            fmt.Println(sa[i].num)
            fmt.Println(CToGoString(sa[i].food[:]))
            fmt.Println(CToGoString(sa[i].animal[:]))
        }
    }
    

    Output:

    $ go run sample.go
    10
    noodle
    cat
    20
    pizza
    dog
    
    评论

报告相同问题?

悬赏问题

  • ¥15 有赏,i卡绘世画不出
  • ¥15 如何用stata画出文献中常见的安慰剂检验图
  • ¥15 c语言链表结构体数据插入
  • ¥40 使用MATLAB解答线性代数问题
  • ¥15 COCOS的问题COCOS的问题
  • ¥15 FPGA-SRIO初始化失败
  • ¥15 MapReduce实现倒排索引失败
  • ¥15 ZABBIX6.0L连接数据库报错,如何解决?(操作系统-centos)
  • ¥15 找一位技术过硬的游戏pj程序员
  • ¥15 matlab生成电测深三层曲线模型代码