简体   繁体   中英

Swift: Turning a String into UnsafeMutablePointer<Int8>

I have a C function mapped to Swift defined as

predictX010(inputString: UnsafePointer<emxArray_char_T>!, ypred: UnsafeMutablePointer<emxArray_real_T>!)

I want to input a string in the inputString, but in order to do that I have to play around with emxArray_char_T which is

emxArray_char_T.init(data: UnsafeMutablePointer<Int8>!, size: UnsafeMutablePointer<Int32>!, allocatedSize: Int32, numDimensions: Int32, canFreeData: boolean_T)

My string will consist of let x = ":1580222503,GCP001,007,Male,30,Left,1,IL8 and IL10,0000; 0,281411,-78,521074,-3,344657,132,347776,-93,25,44" and I just cannot figure out how to input it in data of the emxArray_char_T

First you should write a wrapper function in your bridging header that accepts char pointers then cast/create the emxArray_char_T in c IE:

// casting the func as void because you didn't specify

void predictWrapper(const char *aChar, char *bChar) {
    // do your casting and call original func predictX010(...)
}

Then in swift (This isn't going to be pretty)

var arg: String = "some arg"
var arg2: String = "another arg"

// use closure to prevent dangling pointer
arg.withCString{ body in // body is UnsafePointer<Int8>
    arg2.withCString{ body2 in // we'll cast this to UnsafeMutablePointer
        var arg2Mutable = UnsafeMutablePointer<Int8>(mutating: body2)
        //call your wrapper
        predictWrapper(body, arg2Mutable)
        
    }
}

You may be able to use the original types and function, but i've always found it easier (less banging my head on the desk) to use the most standard c types you can in swift and casting to custom/complex types in c

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM