【问题标题】:How to access global variable in cgo?如何在cgo中访问全局变量?
【发布时间】:2019-01-18 02:03:49
【问题描述】:

结构的内存已经分配了。

我想在 golang 中使用 C 结构。

我想在没有c代码的情况下访问golang中的struct变量,我该怎么办?

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

我已经写了这个例子。

【问题讨论】:

    标签: go cgo


    【解决方案1】:

    例如,

    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[:]))
        }
    }
    

    输出:

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

    【讨论】:

    • 哇!非常感谢!!你的意思是“var sa * [2] C.sample”还是可以是动态的?
    • @botob:查看我修改后的答案:var sa []C.sample
    猜你喜欢
    • 2016-05-04
    • 1970-01-01
    • 1970-01-01
    • 2015-03-30
    • 1970-01-01
    • 2012-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多