ㄷㅣㅆㅣ's Amusement

[Swift] How to convert from void* to char* 본문

Programming/iOS

[Swift] How to convert from void* to char*

ㄷㅣㅆㅣ 2017. 9. 5. 15:48

[Swift] How to convert from void* to char*

How to convert from void* to char*


I had to use f**king idiot library which is written by C++ in Swift project.

That library use void* for call back function to return.

(There are so many call back event, but that library use only one function pointer (returning void*) like above.) 

1
2
typedef void (* ANY_CB)(void *);
void registerListener(ANY_CB *cbs, ANY_CB cb, ANY_EVENT event);
cs


And I faced to problem.

The library call back with some log. so I had to convert void* to char*, then convert to String. because We need to check the library logs on Xcode console.


The solution is very simple. but I could find it nowhere..

(I try to convert UnsafeMutableRawPointer to UnsafeMutablePointer<CChar>, but I failed)

so I post this blog.

1
2
3
4
5
6
7
registerListener(listener, { (log) in
    guard let log = log else { return }
            
    let opaquePtr = OpaquePointer(log)
    let logPtr = UnsafeMutablePointer<CChar>(opaquePtr)
    AISTTSManager.shared.onInfo(log: String(cString: logPtr))
}, ON_EVENT)
cs


If you use OpaquePointer, then you can convert it to any other pointer. That's it!!

0 Comments
댓글쓰기 폼