Search code examples
cswiftswift2libxml2

Swift2 @convention(c) with char* and type**


I am trying to write pointers to c method as such:

//c signature:
typedef void (*startDocumentSAXFunc) (void *ctx);

//Swift2 working code 
let startDocument: @convention(c) (UnsafeMutablePointer<Void>) -> Void  = { (ctx) -> Void in
    NSLog("Start Document")

}
  • I can't find what type to use for xmlChar**
    //c signature
    typedef void (*startElementSAXFunc) (void *ctx,
                const xmlChar *name,
                const xmlChar **atts);

    //Swift2 code
    let startElement: @convention(c) (UnsafeMutablePointer, UnsafePointer, ???) -> Void  = { (ctx, name, attributes) -> Void in
        NSLog("Start Element \(name), \(attributes)")
    }
  • I can't find what type to use for const char*
    //c signature
    typedef void (XMLCDECL *errorSAXFunc) (void *ctx,
                const char *msg, ...);

    //Swift2
     let error: @convention(c) (UnsafeMutablePointer, ???) -> Void =
    { (ctx, msg) -> Void in
        NSLog("Error \(msg)")
    }

I tried the type UnsafePointer<CChar> but it is not working.

The aim here is to be able to use the libXML which is quicker than NSXML lib.

Thanks for your help !


Solution

  • check this 'self explanatory' example

    let str = "A"
    var c = str.utf8.map { (c) -> CChar in
        return CChar(c)
    }[0]
    print(c, c.dynamicType)  // 65 Int8
    
    var p = UnsafeMutablePointer<CChar>.alloc(1)
    print(p.memory, p.memory.dynamicType) // 0 Int8
    p.memory = 65
    
    func modify(pp: UnsafeMutablePointer<UnsafeMutablePointer<CChar>>)->Void {
        print(pp.memory.memory, pp.memory.memory.dynamicType)
    }
    
    let pp = withUnsafeMutablePointer(&p){ $0 }
    print(pp, pp.dynamicType) // 0x0000000119bbf750 UnsafeMutablePointer<UnsafeMutablePointer<Int8>>
    
    modify(pp) // 65 Int8
    

    ...

    p.dealloc(1)
    modify(pp) // -107 Int8
    // -107 is some 'random' value, becase the memory there was dealocated!!
    

    UnsafePoiner<CChar> is const char * while UndafeMutablePointer<CChar> is char * etc ...