swiftpointersswiftuiffiunsafemutablepointer

Export SwiftUI View via UnsafeMutableRawPointer


I'd like to return a SwiftUI Text View as an UnsafeMutableRawPointer, abiding by the C calling convention, so another language can FFI into it for use.

@_cdecl("hi")
func hi (txt: UnsafeMutablePointer<CChar>) -> () {
   var view = ViewBuilder.buildBlock(Text(String(cString: txt)))
   return UnsafeMutableRawPointer(Unmanaged.passUnretained(view).toOpaque())
}

But I am receiving the following error:

Cannot invoke 'passUnretained' with an argument list of type '(Text)'

How can get at the underlying pointer of a SwiftUI Text object ?


Solution

  • Wrap it by your own class

    @_cdecl("hi")
    func hi (txt: UnsafeMutablePointer<CChar>) -> UnsafeMutableRawPointer {
       let view = ViewBuilder.buildBlock(Text(String(cString: txt)))
        return UnsafeMutableRawPointer(Unmanaged.passUnretained(Wrapper(text: view)).toOpaque())
    }
    
    final class Wrapper {
        let text: Text
        init(text: Text) {
            self.text = text
        }
    }