[swift-users] String init from Int8 tuple?

Rick Mann rmann at latencyzero.com
Tue Apr 18 20:11:53 CDT 2017


In my C-interop, I have a need to do this a lot:

typedef struct {
    char message[LGS_MAX_MESSAGE_SIZE];
    ...other stuff...
} lgs_result_info_t;

func
callbackFailed(info inInfo: lgs_result_info_t)
{
    var m = inInfo.message	// *See note below
    let message: String = withUnsafePointer(to: &m)
    { inArg -> String in
        return String(cString: UnsafeRawPointer(inArg).assumingMemoryBound(to: Int8.self))
    }
    debugLog("Failed: \(message)")
}

I'd like to do something like this:

extension
String
{
    init<T>(withUnsafePointerTo inPtr: T)
    {
        withUnsafePointer(to: &inPtr)
        { inArg in
             init(cString: UnsafeRawPointer(inArg).assumingMemoryBound(to: Int8.self))
        }
    }
}

But I can't get that to compile.

Help is greatly appreciated.


---
*I can't pass inInfo directly to withUnsafePointer, because it says "Cannot pass immutable value as inout argument: 'inInfo' is a 'let' constant"

-- 
Rick Mann
rmann at latencyzero.com




More information about the swift-users mailing list