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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With