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?
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