logo
down
shadow

Convert String to UnsafeMutablePointer<char_t> in Swift


Convert String to UnsafeMutablePointer<char_t> in Swift

By : Tom Boersma
Date : November 22 2020, 10:48 AM
should help you out It all depends on what char_t is.
If char_t converts to Int8 then the following will work.
code :
if let cString = str.cStringUsingEncoding(NSUTF8StringEncoding) {
    some_c_func(strdup(cString))
}
some_c_func(strdup(str.cStringUsingEncoding(NSUTF8StringEncoding)!))
guard let cString = str.cString(using: .utf8) else {
    return
}

some_c_func(cString)
guard let interimString = str.cString(using: .utf8), let cString = strdup(interimString) else {
    return
}

some_c_func(cString)

//…

free(cString)


Share : facebook icon twitter icon
Swift convert string to UnsafeMutablePointer<Int8>

Swift convert string to UnsafeMutablePointer<Int8>


By : cavalier123
Date : March 29 2020, 07:55 AM
it should still fix some issue
Previous answers on StackOverflow using CString don't seem to work anymore
code :
let s = NSBundle.mainBundle().bundlePath
let cs = (s as NSString).UTF8String
var buffer = UnsafeMutablePointer<Int8>(cs)
swe_set_ephe_path(buffer)
func swe_set_ephe_path(path: UnsafeMutablePointer<Int8>) {
    println(String.fromCString(path))
}
iOS: Convert UnsafeMutablePointer<Int8> to String in swift?

iOS: Convert UnsafeMutablePointer<Int8> to String in swift?


By : Muhamad El-shamy
Date : March 29 2020, 07:55 AM
I wish did fix the issue. If the pointer points to a NUL-terminated C string of UTF-8 bytes, you can do this:
code :
import Foundation

let x: UnsafeMutablePointer<Int8> = ...
// or UnsafePointer<Int8>
// or UnsafePointer<UInt8>
// or UnsafeMutablePointer<UInt8>

let str = String(cString: x)
Swift: Cannot convert value of type 'UnsafeMutablePointer' to expected argument type 'UnsafeMutablePointer'

Swift: Cannot convert value of type 'UnsafeMutablePointer' to expected argument type 'UnsafeMutablePointer'


By : B.J. Waples
Date : March 29 2020, 07:55 AM
should help you out I have a little Problem with my Code after updating to Swift 3. I had this Code before the conversion: , copyBytes expects a UnsafeMutableBufferPointer as argument:
code :
extension Data {
    func castToCPointer<T>() -> T {
        let mem = UnsafeMutablePointer<T>.allocate(capacity: 1)
        _ = self.copyBytes(to: UnsafeMutableBufferPointer(start: mem, count: 1))
        return mem.move()
    }
}
extension Data {
    func castToCPointer<T>() -> T {
        let mem = UnsafeMutablePointer<T>.allocate(capacity: 1)
        _ = self.copyBytes(to: UnsafeMutableBufferPointer(start: mem, count: 1))
        let val =  mem.move()
        mem.deallocate(capacity: 1)
        return val
    }
}
extension Data {
    func castToCPointer<T>() -> T {
        return self.withUnsafeBytes { $0.pointee }
    }
}
How to convert String to UnsafeMutablePointer<UInt8> ? Swift 3

How to convert String to UnsafeMutablePointer<UInt8> ? Swift 3


By : Kana de rycke
Date : March 29 2020, 07:55 AM
Hope this helps This is where you run into some complexity from having to work with C.
The primary concern here is the life time of the pointers you pass into that function. My code below uses pointers into the buffer of the Swift Strings. This will be an issue if the areKeysConsistent captures those pointers for later use. It's possible that ARC deallocates the Swift String, making those stored pointers become dangling pointers.
code :
func areKeysConsistent(
        _ cert: UnsafeMutablePointer<UInt8>, _ certLength: Int,
        _ key: UnsafeMutablePointer<UInt8>, _ keyLength: Int,
        _ pass: UnsafeMutablePointer<UInt8>, _ passLength: Int
    ) {
    print(cert, key, pass)
}

let certificate = "cert"
let privateKey = "key"
let password = "password"

var certificateCString = certificate.utf8CString
var privateKeyCString = privateKey.utf8CString
var passwordCString = password.utf8CString


certificateCString.withUnsafeMutableBytes { certUMRBP in
privateKeyCString.withUnsafeMutableBytes { pkUMRBP in
passwordCString.withUnsafeMutableBytes { passUMRBP in

    areKeysConsistent(
        certUMRBP.baseAddress!.bindMemory(to: UInt8.self, capacity: certUMRBP.count),
        certUMRBP.count,
        pkUMRBP.baseAddress!.bindMemory(to: UInt8.self, capacity: pkUMRBP.count),
        pkUMRBP.count,
        passUMRBP.baseAddress!.bindMemory(to: UInt8.self, capacity: passUMRBP.count),
        passUMRBP.count
    )
}
}
}
Swift 4 convert String to UnsafeMutablePointer<Int8>

Swift 4 convert String to UnsafeMutablePointer<Int8>


By : dave
Date : March 29 2020, 07:55 AM
seems to work fine Follow up and Summary:
1) solution in link Swift convert string to UnsafeMutablePointer is not valid in Swift 4 anymore.
code :
let contentPointer = strdup(content)
let contentPointer = strdup(content)
SendPing(content: contentPointer)
....

free(contentPointer)
Related Posts Related Posts :
  • consecutive statement need to have ; error in swift
  • Trying to create a 32 bpc NSBitmapImageRep, getting hit with errors
  • Does locationManager:didUpdateLocations: method called at the same time in extension and its containing app
  • Can't get Data using SwiftyJSON
  • inout param with empty object since nil won't work
  • How to align a mask onto an image
  • compiler forcing self inside static method of a function while using dispatch_sync
  • private static variable in struct
  • Conditional "in" for arrays in Swift
  • Extension for Double to accept String as initializer in Swift
  • Modifying UIButton Programmatically
  • Pass type to generic function and compare
  • How to customise the look of the PFSignUpViewController
  • How to take screen shot programmatically (Swift, SpriteKit)
  • Setting NavigationController's NavigationBar translucent property to false causes extra padding
  • Create multiple UIViews when the user taps the screen
  • Filter Array of [AnyObject] in Swift
  • How to add ParseUI to a swift project
  • Can Swift enums have multiple raw values?
  • Using a function() variable in a different Class - Swift
  • Masking an image in Swift using CALayer and UIImage
  • KVC without NSObject (NSPredicate)
  • Any? to Dictionary Cast and retrieving value
  • NSCharacterSet.characterIsMember() with Swift's Character type
  • SCNScene: Calculate projected size of an object
  • How to use contains on a swiftyJSON object
  • Index of element in sorted()
  • How do I initialise a new NSDocument instance in Swift?
  • Multiple functions with the same name
  • shadow
    Privacy Policy - Terms - Contact Us © ourworld-yourmove.org