Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

too few values in struct initializer when initialize C struct in golang

Tags:

go

cgo

I have tried the following program, but it told me "too few values in struct initializer" when compiling it.

package main

/*
#include <stdlib.h>
struct Person {
    char *name;
    int age;
    int height;
    int weight;
};
*/
import "C"
import "fmt"

type p C.struct_Person

func main() {

    person := p{C.CString("Giorgis"), 30, 6, 175}
    fmt.Println(person)
    fmt.Println(C.GoString(person.name))
    fmt.Println(person.age)
    fmt.Println(person.height)
    fmt.Println(person.weight)
}

How can I fix this wired problem? Additionally, when I changed type "char*" to "char", and the initializer. It works well.

struct Person {
    char name;
    int age;
    int height;
    int weight;
};

Also, when I use

struct Person {
    char *name;
};

it works well too.

Anyway, how can I fix it? Thanks.

like image 351
Wyatt Avatar asked Mar 24 '16 08:03

Wyatt


1 Answers

Please try to put the field names in your struct literal.

person := p{name: C.CString("Giorgis"), age: 30, height: 6, weight: 175}

This is because an anonymous 4-byte padding field gets inserted between name and age.

like image 52
Sebastian Avatar answered Sep 20 '22 00:09

Sebastian