在 golang 中初始化 C 结构时,结构初始化程序中的值太少
too few values in struct initializer when initialize C struct in golang
我试过下面的程序,但是在编译的时候它告诉我"too few values in struct initializer"。
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;
};
效果也不错。
无论如何,我该如何解决?谢谢
请尝试将字段名称放在结构文字中。
person := p{name: C.CString("Giorgis"), age: 30, height: 6, weight: 175}
这是因为在姓名和年龄之间插入了一个匿名的 4 字节 padding 字段。
我试过下面的程序,但是在编译的时候它告诉我"too few values in struct initializer"。
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;
};
效果也不错。
无论如何,我该如何解决?谢谢
请尝试将字段名称放在结构文字中。
person := p{name: C.CString("Giorgis"), age: 30, height: 6, weight: 175}
这是因为在姓名和年龄之间插入了一个匿名的 4 字节 padding 字段。