0

I need to do the following C casting in Swift (4):

struct A ** castme = input
struct B * tothis = (struct B *)castme

In Swift, castme type is UnsafeMutablePointer<UnsafeMutablePointer<A>?>!

I assume I am trying to cast to UnsafeMutablePointer<B>! ?

Also, would it be correct to say that I could also cast *(castme) to a (struct B) directly? If yes, would it make casting easier by casting from UnsafeMutablePointer<A>? to B ?

I saw this thread but wasn't able to get what I needed from it: Cast to different C struct unsafe pointer in Swift

agirault
  • 2,509
  • 20
  • 24

1 Answers1

2

Let's think about that in terms of what's happening in C. When I do a cast of pointers in C, the data that represents the pointer type will now be treated as a pointer of a different type. The value of the pointer doesn't change, just how you treat it.

Swift doesn't like to do this kind of thing and doesn't encourage you to do it because while cheap, it's a fundamentally unsafe thing to do and can lead to corrupting data, jumping into space, bus errors, etc.

That doesn't mean that swift doesn't have the ability to do this. The link that you point to uses withUnsafePointerTo which tries to limit the scope of the use of the pointer. In your case, you probably want to look at unsafeBitCast (documentation here) which mimics the C pointer cast (it's not strictly the same as C casting in general, but for pointers it is).

let a:UnsafeMutablePointer<SomeType> = fetchASomeTypePointer()
let b = unsafeBitCast(a, to: UnsafeMutablePointer<SomeOtherType>.self)

This makes the data representing the pointer to SomeType now become a pointer to SomeOtherType.

Like I said before, this is a dangerous thing to do especially if you don't fully understand what you're doing.

plinth
  • 48,267
  • 11
  • 78
  • 120