Is it possible to convert a Swift class to a C void * pointer?

Is it possible to convert the Swift class to C void * pointer?

// swift class class MyClass { } var myClass = MyClass() var p: UnsafeMutablePointer<Void> = myClass //<- failed //c function void someSwiftClass(void *context); 

thanks

+5
source share
3 answers

I had a similar problem, you can convert it as shown below.

 var myClass = MyClass() var classPtr = unsafeBitCast(myClass, UnsafePointer<Void>.self) 

and your function,

 func someSwiftClass(voidPointer: UnsafeMutablePointer<Void>) { } 

If you want to declare a constant pointer, use UnsafePointer<T> , and when your pointer is not constant, use UnsafeMutablePointer<T>

In the constant pointer C - const int *myCpointer

The corresponding quick pointer is let mySwiftPointer: UnsafePointer<Int32>

+3
source

It works:

 var p: UnsafeMutablePointer<Void> = UnsafeMutablePointer(Unmanaged.passUnretained(myClass).toOpaque()) 
+1
source

I did some testing using Swift 2. The behavior in Swift 2 may be different from previous versions of Swift, but here's what I found.

The solutions proposed by Amit89 and newacct will compile, but there may be problems using an instance of MyClass in C code. Something like this

 someSwiftClass(&myClass) 

will also compile just fine, but with the same problem.

I do not know the context of the original question, but let me guess that the C code will do something with void * passed to someSwiftClass (), so there is an instance of some type of C that is supposed to point to a pointer to. As my experience shows, in this case it is safer to import the C data type, most likely the structure, into Swift and either use this imported type for all your Swift code, or use some Swift class / struct shell. You can write a wrapper to wrap UnsafeMutablePointer, in which case changes made to the data in Swift code will be visible in C!

Please see this question for more information: Swift converts uint64_t to C, different from using its own UInt64 type

I also have a blog post that may come in handy: http://www.swiftprogrammer.info/callback_void.html

0
source

All Articles