In Swift we have a powerful high-level logic abstraction, while low-level operations are deliberately limited. But in some cases we still want to do some hack work in C, and the cat will take a look at how to do it.
Hacking is happy!!! ;]
As the title says, now I have an int variable x, I want to get its address, then convert it to char type address, and then change the address of the content +1, if the C language to represent is:
121,*pi = &xchar *pc = (char *)pi1
There are 2 questions to be written with Swift, one is that you cannot directly get a pointer to a variable, and the second is that you cannot directly convert it directly to two different types of pointers, even if you can.
Let's deal with the first problem first, you can't write this:
var121var//error!!!
The problem is not that the & operator, a lot of people may think that Swift does not have a C in the address operator &, but you can actually have, but you can not get the address directly to do the processing.
But there is a way we can use the variant Withunsafemutablepointer method of the Withunsafepointer method to get its address, except that the address is passed as a parameter to the closure you specify. What do you expect if you get an address?
typealias Char = Int8var121var pChar = withUnsafeMutablePointer(&x){(p:UnsafeMutablePointer<Int>)->in //???}
As the above code, we just return a char pointer in the closure, how to do it?
This requires the help of another super-powerful (you know what "strong" means here;]) Method Unsafebitcast, the method casts one type of variable content to another, and the above closures//??? Replace with the following code:
returnUnsafeMutablePointer<Char>.self)
OK, let's test it out:
Note the last line of the last digit 377,x why did it change from 121 to 377? Here is not explained, because often play assembly or C's small partners must have been clear in the heart bird!;]
How to convert different types of mutable pointers in Swift