I was wondering if there is a nice way to convert from *int to *C.int, that works across different architectures with different word sizes?
(*C.int)(&a) fails to compile (on a x86_64 system) while I feel (*C.int)(unsafe.Pointer(&a)) is dangerous. My current workaround involves using reflect:
var retVal int
var a C.int
size := reflect.TypeOf(a).Size()
switch size {
case 2:
var tmp int16
C.cgocall((*C.int)(&tmp))
retVal = int(tmp)
case 4:
var tmp int32
C.cgocall((*C.int)(&tmp))
retVal = int(tmp)
case 8:
var tmp int64
C.cgocall((*C.int)(&tmp))
retVal = int(tmp)
}
Now, this is ugly as heck (and doesn’t compile). And it adds a lot of touch points to my code which I’m not the best at, and I’d really rather be familiar with my code.
Notice the sizes of the integers are different, but the conversion still worked. Please make sure it works as you expect on the systems you need to run on. I think the values will be truncated, but that could still be bad.
Yeah, turns out there is no way to do pointer-to-pointer conversion without being unsafe. It will always need a conversion from int to C.int as they’re different types.