在golang中初始化C结构时,结构初始化器中的值太少。

huangapple go评论91阅读模式
英文:

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

问题

我尝试了以下程序,但在编译时它告诉我“结构初始化器中的值太少”。

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

我该如何解决这个奇怪的问题?另外,当我将类型“char*”更改为“char”,并更改初始化器时,它可以正常工作。

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

此外,当我使用

struct Person {
    char *name;
};

也可以正常工作。

无论如何,我该如何解决它?谢谢。

英文:

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

package main

/*
#include &lt;stdlib.h&gt;
struct Person {
    char *name;
    int age;
    int height;
    int weight;
};
*/
import &quot;C&quot;
import &quot;fmt&quot;

type p C.struct_Person

func main() {

    person := p{C.CString(&quot;Giorgis&quot;), 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.

答案1

得分: 6

请尝试在结构体字面量中添加字段名。

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

这是因为在name和age之间会插入一个匿名的4字节填充字段。

英文:

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

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

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

huangapple
  • 本文由 发表于 2016年3月24日 16:31:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/36195935.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定