英文:
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 <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.
答案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("Giorgis"), age: 30, height: 6, weight: 175}
This is because an anonymous 4-byte padding field gets inserted between name and age.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论