英文:
Go type for conversion to *ptrdiff_t?
问题
在我的Go程序中,我调用了一个C函数,我可以成功地将int
转换为ptrdiff_t
。(有点令人担忧的是,即使Go类型对于任何现代架构来说都太小,int8
也能成功编译。)然而,*int
到*ptrdiff_t
会导致编译错误:cannot convert <varname> (type *int) to type *_Ctype_ptrdiff_t
。唯一允许成功编译的类型是int64
。我意识到我可以将变量声明为(*)C.ptrdiff_t
,但我想了解适当的对应Go类型以及Go编译器在这种情况下的意外行为。
英文:
In my Go program where I'm invoking a C function I can successfully convert from int
to ptrdiff_t
. (Somewhat concerningly even int8
will compile successfully even though the Go type is far too small for any modern architecture.) However *int
to *ptrdiff_t
yields a compiler error: cannot convert <varname> (type *int) to type *_Ctype_ptrdiff_t
. The only type that permits successful compilation is int64
. I realize I can declare my variable as (*)C.ptrdiff_t but I want to understand the appropriate corresponding Go type and the unexpected behavior of the Go compiler in this instance?
答案1
得分: 2
ptrdiff_t是一种特定大小的整数类型。当你将另一种整数类型转换为ptrdiff_t时,编译器会重新调整整数的大小。换句话说,它会改变旧整数的内存表示以匹配新的类型。然后,这个新的表示被放置在内存中的不同位置。
指针是内存中的一个位置。因此,你只能将其转换为指向相同内存布局的类型。int64与ptrdiff_t具有相同的大小,因此内存表示相同,指针可以自由转换。
如果你想转换任意整数类型,你需要首先改变它的内存表示,并通过将其赋值给一个变量并取其指针来给它一个新的位置。
newtype := ptrdiff_t(oldInt)
pnewtype := &newtype
英文:
A ptrdiff_t is an integer type of a particular size. When you convert another integer type to a ptrdiff_t, the compiler re-sizes the integer. In other words, it changes the memory representation of the old integer to match the new type. This new representation is then put in a different location in memory.
A pointer is a location in memory. Therefore, you can only convert to a type that points to the same memory layout. An int64 has the same size as a ptrdiff_t so the memory representation is the same and the pointer can be converted freely.
If you wish to convert an arbitrary integer type, you need to first change its in memory representation and give it a new location by assigning it to a variable and taking its pointer.
newtype := ptrdiff_t(oldInt)
pnewtype := &newtype
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论