转换为*ptrdiff_t的Go类型是什么?

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

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 &lt;varname&gt; (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 := &amp;newtype

huangapple
  • 本文由 发表于 2014年1月19日 08:28:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/21211688.html
匿名

发表评论

匿名网友

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

确定