Comparing OpaquePointer to Int32

I have the following OpaquePointer:

VK_DEFINE_HANDLE(VkCommandBuffer)

where

#define VK_DEFINE_HANDLE(object) typedef struct object##_T* object;

and

#define VK_NULL_HANDLE 0

On C you can check a VkCommandBuffer against VK_NULL_HANDLE, how can I do that on Swift?

The VkCommandBuffer should be imported as OpaquePointer?, in which case you can just do == nil.

If, for whatever reason, you don't have the correct nullability being imported, you can do Int32(Int(bitPattern: ptr)) where ptr is an OpaquePointer to convert it to an Int32; however, the better option is to fix the nullability. You may have NS_ASSUME_NONNULL being defined somewhere where it shouldn't be, for example.

Edit: oops, as @jrose says, Int(bitPattern: ptr) is safe but the conversion to Int32 afterwards is most definitely not. The Int32 should be converted to an Int before comparison if you’re going that route.

1 Like

Er, please don't convert a pointer to Int32. That's one of the things "64-bit" usually means: pointers are 64 bits, and converting most of them to Int32 will fail (trap at runtime) or lose information.

8 Likes
Terms of Service

Privacy Policy

Cookie Policy