int 和 C.int 有什么区别?
What's the difference between int and C.int in go?
import "C"
func f() {
var vGo int
var vC C.int
// fails to compile with error
// cannot use &vGo (type *int) as type *C.int in argument to...
C.c_function(&vGo)
// compiles just fine:
C.c_function(&vC)
}
我用CGO_ENABLED=1 GOARCH=arm编译...
在这种情况下,int 和 C.int 类型有什么不同?
我在哪里可以找到有关 GO 中 C 类型的更多信息?
类型之间有什么区别?这取决于。如果您使用的是 64 位,则 Go int 将为 64 位,而 C int 将为 32 位。如果您使用的是 32 位,则没有真正的区别。
我在哪里可以找到有关 Go 中 C 类型的更多信息?查看 C 的文档。如评论中所述,Go 中不允许隐式数字类型转换,因此需要进行转换。
Go 故意不支持隐式类型转换,但有一些例外1:
A value x is assignable to a variable of type T ("x is assignable to T") in any of these cases:
- x's type is identical to T.
- x's type V and T have identical underlying types and at least one of V or T is not a named type.
- T is an interface type and x implements T.
- x is a bidirectional channel value, T is a channel type, x's type V and T have identical element types, and at least one of V or T is not a named type.
- x is the predeclared identifier nil and T is a pointer, function, slice, map, channel, or interface type.
- x is an untyped constant representable by a value of type T.
您需要进行转换以匹配可能不同的内存布局2。
import "C"
func f() {
var vGo int
var vC C.int
// fails to compile with error
// cannot use &vGo (type *int) as type *C.int in argument to...
C.c_function(&vGo)
// compiles just fine:
C.c_function(&vC)
}
我用CGO_ENABLED=1 GOARCH=arm编译...
在这种情况下,int 和 C.int 类型有什么不同?
我在哪里可以找到有关 GO 中 C 类型的更多信息?
类型之间有什么区别?这取决于。如果您使用的是 64 位,则 Go int 将为 64 位,而 C int 将为 32 位。如果您使用的是 32 位,则没有真正的区别。
我在哪里可以找到有关 Go 中 C 类型的更多信息?查看 C 的文档。如评论中所述,Go 中不允许隐式数字类型转换,因此需要进行转换。
Go 故意不支持隐式类型转换,但有一些例外1:
A value x is assignable to a variable of type T ("x is assignable to T") in any of these cases:
- x's type is identical to T.
- x's type V and T have identical underlying types and at least one of V or T is not a named type.
- T is an interface type and x implements T.
- x is a bidirectional channel value, T is a channel type, x's type V and T have identical element types, and at least one of V or T is not a named type.
- x is the predeclared identifier nil and T is a pointer, function, slice, map, channel, or interface type.
- x is an untyped constant representable by a value of type T.
您需要进行转换以匹配可能不同的内存布局2。