Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

// swift class
 class MyClass {

 }

var myClass = MyClass()
var p: UnsafeMutablePointer<Void> = myClass //<- failed

//c function 
void someSwiftClass(void *context);

Thanks

like image 913
CocoaUser Avatar asked Sep 27 '22 20:09

CocoaUser


2 Answers

I had similar problem, you can convert this as below.

var myClass = MyClass()

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

and your function,

func someSwiftClass(voidPointer: UnsafeMutablePointer<Void>) {

}

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

In C constant pointer - const int *myCpointer

Corresponding swift pointer - let mySwiftPointer: UnsafePointer<Int32>

like image 101
Amit89 Avatar answered Oct 18 '22 10:10

Amit89


This works:

var p: UnsafeMutablePointer<Void> =
    UnsafeMutablePointer(Unmanaged.passUnretained(myClass).toOpaque())
like image 28
newacct Avatar answered Oct 18 '22 11:10

newacct