Consider the following code:
dim i64 as Int64 = 1234567 dim i32 as int32 = 7654321 i32 = Int32(i64) // cast i64 = Int64(i32) // cast i32 = Ctype(i64, Int32) // convert i64 = Ctype(i32, Int64) // convert
It all seems reasonable enough. Not useful, but seems reasonable. Only one problem. It won’t compile. Why not? The two casts to int32 and int64 will fail. Now why is that?
A cast assumes that what you are casting is, at the very least, the SAME SIZE.
Casts have several requirements:
- Objects can be cast to different classes or interfaces.
- Integers and unsigned integers can be cast to and from enumerations of the same size.
- Int32 can be cast to and from Color.
- Integer and UInteger can be cast to and from Ptr .
dim i32 as int32 = 7654321 dim ui32 as Uint32 ui32 = UInt32(i32)
will be just fine.
But there are limits.
dim i64 as Int64 = 1234567 dim d as double = Double(i64)
This code won’t work at all even though a double and int64 are both 8 bytes (an implementation detail that really isn’t relevant in Xojo). A cast never converts the value, or otherwise changes its runtime type. It can only make the value’s static (compile-time) type more specific. You can cast an object reference from a superclass to a subclass, or from an interface type to an implementation type, or from an integer to another integer type of the same size.
So you can’t cast from an int64 to a double – that requires converting the value.
Ctype can do these conversions as it’s not just reinterpreting the bytes. it’s explicitly converting from one type to another. But it can only do this for types that can actually be converted from one to the other. You can’t convert a string into an integer using CType. For that you need to use other functions like Integer.FromText orĀ Val().
As more and more code needs to function in both 32 and 64 bit worlds, this may become increasingly important especially with declares that access external code. Questions about this? Ask me here or find me on the Xojo Forums.