Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access global variable in cgo?

Tags:

go

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.

like image 343
botob Avatar asked Oct 16 '22 08:10

botob


1 Answers

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
like image 171
peterSO Avatar answered Oct 20 '22 05:10

peterSO