logo
Tags down

shadow

Any way to detect `UnsafeMutablePointer` has been deallocated?


By : Sérgio Martins
Date : September 16 2020, 06:00 AM
I think the issue was by ths following , No; it is your responsibility to ensure that an unsafe pointer cannot outlive its referenced object. ("Important memory details are your problem" is what Swift generally means by the "Unsafe" designation.)
Generally the correct tool here is a weak reference rather than a pointer.
code :


Share : facebook icon twitter icon

How to create a UnsafeMutablePointer<UnsafeMutablePointer<UnsafeMutablePointer<Int8>>>


By : Zhenya
Date : March 29 2020, 07:55 AM
will be helpful for those in need Generally, if a function takes a UnsafePointer parameter then you can pass a variable of type T as in "inout" parameter with &. In your case, T is
code :
UnsafeMutablePointer<UnsafeMutablePointer<Int8>>
var prediction : UnsafeMutablePointer<UnsafeMutablePointer<Int8>> = nil
if presage_predict(prsg, &prediction) == PRESAGE_OK { ... }
presage_free_string_array(prediction)
// Duplicate the C strings to avoid premature deallocation:
let past = strdup("did you not sa")
let future = strdup("")

func get_past_stream(arg: UnsafeMutablePointer<Void>) -> UnsafePointer<Int8> {
    return UnsafePointer(past)
}

func get_future_stream(arg: UnsafeMutablePointer<Void>) -> UnsafePointer<Int8> {
    return UnsafePointer(future)
}

var prsg = presage_t()
presage_new(get_past_stream, nil, get_future_stream, nil, &prsg)

var prediction : UnsafeMutablePointer<UnsafeMutablePointer<Int8>> = nil
if presage_predict(prsg, &prediction) == PRESAGE_OK {

    for var i = 0; prediction[i] != nil; i++ {
        // Convert C string to Swift `String`:
        let pred = String.fromCString(prediction[i])!
        print ("prediction[\(i)]: \(pred)")
    }

    presage_free_string_array(prediction)
}

free(past)
free(future)
prediction[0]: say
prediction[1]: said
prediction[2]: savages
prediction[3]: saw
prediction[4]: sat
prediction[5]: same

Creating an UnsafeMutablePointer<UnsafeMutablePointer<Float>> parameter in Swift 3


By : Asddev
Date : March 29 2020, 07:55 AM
will help you When you need to pass multiple values for UnsafeMutablePointer parameters, you need to declare a variable of type [T] (aka Array) and pass it as an inout argument. In your case T is UnsafeMutablePointer.
So, if you want to start with [Float], you may need to write something like this:
code :
let input: [Float] = [/*...*/]
var output: [Float] = Array(repeating: 0, count: outputTotalSize)
input.withUnsafeBufferPointer {inBuf in
    let inputPtr = inBuf.baseAddress!
    output.withUnsafeMutableBufferPointer {outBuf in
        let outputPtr = outBuf.baseAddress!
        var pInputs: [UnsafePointer<Float>] = [inputPtr,/*...*/]
        var pOutputs: [UnsafeMutablePointer<Float>] = [outputPtr/*...*/]
        vDSP_biquadm(setup, &pInputs, inStride, &pOutputs, outStride, length)
    }
}

UnsafeMutablePointer to expected argument type UnsafeMutablePointer<_> in Swift 3


By : a7a7p
Date : March 29 2020, 07:55 AM
I wish this help you Basically, this is a variant on the problem discussed here:
Xcode 8 beta 6: main.swift won't compile
code :
    startup(
        CommandLine.argc,
        UnsafeMutableRawPointer(CommandLine.unsafeArgv)
            .bindMemory(
                to: Optional<UnsafePointer<Int8>>.self,
                capacity: Int(CommandLine.argc))
    )

CoreGraphics - Can't replace UnsafeMutablePointer<UInt32> with UnsafeMutablePointer<UInt8>


By : Sania Reva
Date : March 29 2020, 07:55 AM
wish helps you I just started messing around with image processing and I'm having a couple very odd problems or at least I think they are. I'm assuming I've made some really dumb mistake. , One thing critically bad in your code is this line:
code :
    defer { data.deallocate(capacity: totalBytes) }
private func grayScalePixels() -> UnsafeMutableBufferPointer<UInt8>? {
    guard let cgImage = self.cgImage else { return nil }

    let bitsPerComponent = 8
    let width = cgImage.width
    let height = cgImage.height
    let totalBytes = width * height
    let colorSpace = CGColorSpaceCreateDeviceGray()
    let data = UnsafeMutablePointer<UInt8>.allocate(capacity: totalBytes)
    data.initialize(to: UInt8.max, count: totalBytes)   //<- #4

    guard let imageContext = CGContext(data: data, width: width, height: height, bitsPerComponent: bitsPerComponent, bytesPerRow: width, space: colorSpace, bitmapInfo: 0) else { return nil }
    imageContext.draw(cgImage, in: CGRect(x: 0, y: 0, width: width, height: height))

    return UnsafeMutableBufferPointer(start: data, count: totalBytes)
}

public func normalizedGrayScalePixels() -> [CGFloat]? {
    guard let cgImage = self.cgImage else { return nil }
    guard let pixels = self.grayScalePixels() else { return nil }

    let width = cgImage.width
    let height = cgImage.height
    var result: [CGFloat] = []

    for y in 0..<height {
        for x in 0..<width {
            let index = width * y + x
            let pixel = CGFloat(pixels[index]) / CGFloat(UInt8.max)
            result.append(pixel)
        }
    }
    pixels.baseAddress!.deinitialize(count: pixels.count)   //<- #2
    pixels.baseAddress!.deallocate(capacity: pixels.count)  //<- #1

    return result
}
private func grayScalePixels() -> [UInt8]? {
    guard let cgImage = self.cgImage else { return nil }

    let bitsPerComponent = 8
    let width = cgImage.width
    let height = cgImage.height
    let totalBytes = width * height
    let colorSpace = CGColorSpaceCreateDeviceGray()
    var byteArray: [UInt8] = Array(repeating: UInt8.max, count: totalBytes) //<- #4
    let success = byteArray.withUnsafeMutableBufferPointer {(buffer)->Bool in
        guard let imageContext = CGContext(data: buffer.baseAddress!, width: width, height: height, bitsPerComponent: bitsPerComponent, bytesPerRow: width, space: colorSpace, bitmapInfo: 0) else { return false }
        imageContext.draw(cgImage, in: CGRect(x: 0, y: 0, width: width, height: height))
        return true;
    }
    return success ? byteArray : nil
}

public func normalizedGrayScalePixels() -> [CGFloat]? {
    guard let cgImage = self.cgImage else { return nil }
    guard let pixels = self.grayScalePixels() else { return nil }

    let width = cgImage.width
    let height = cgImage.height
    var result: [CGFloat] = []

    for y in 0..<height {
        for x in 0..<width {
            let index = width * y + x
            let pixel = CGFloat(pixels[index]) / CGFloat(UInt8.max)
            result.append(pixel)
        }
    }

    return result
}
    context?.setStrokeColor(gray: 0, alpha: 1)
    data.initialize(to: 0, count: totalBytes)
    var byteArray: [UInt8] = Array(repeating: 0, count: totalBytes)
private func printNumber(rowSize: Int, inputs: Vector) {
    for (index, pixel) in inputs.enumerated() {
        if index % rowSize == 0 { print() }

        if pixel < 1.0 { //<- #4
            print("1", terminator: "")
        }
        else { print(".", terminator: "") }
    }

    print()
}

how to convert UnsafeMutablePointer<UnsafeMutablePointer<Int8>?> to UnsafeMutablePointer<UnsafeMutablePoi


By : Altuğ Şimşek
Date : March 29 2020, 07:55 AM
Hope this helps I am using swift 4.0 to re-write main.swift of my iOS application. And this is my main.swift: , Please check :
code :
UIApplicationMain(  
    CommandLine.argc,  
    UnsafeMutableRawPointer(CommandLine.unsafeArgv)  
        .bindMemory(  
            to: UnsafeMutablePointer<Int8>.self,  
            capacity: Int(CommandLine.argc)
        ),  
    NSStringFromClass(MyAPP.self),  
    NSStringFromClass(AppDelegate.self)  
)  
Related Posts Related Posts :
  • Xcode 11 > Installing (refreshing) Provisioning Profiles crashe
  • In a UIViewControllerRepresentable, how can I pass an ObservedObject's value to the view controller and update it every
  • How to stop infinite loop in swift during action? (iOS)
  • iOS 13 dark mode objc strings
  • How to apply gradient border color to UIButton?
  • Xcode 11.2 - Unable to install App file to device?
  • PHAssetResourceManager writeData Returning Error 1
  • Is there a way to make a checkbox list in flutter where the user can edit the label of that checkbox? For example a task
  • Do i need to create nested struct always for fetching just one property from nested model in json response?
  • BGTaskScheduler submit call fails with BGTaskSchedulerErrorDomain code: 1
  • Clang + iOS + assembler jump: error "unsupported relocation on symbol"
  • How to get listed my ionic app in the share menu in iphone?
  • Does Xcode 11.2 scene editor allow adding components?
  • 'Unable to determine Swift version for the following pod" - Error
  • Could not complete submission of dSYM When fabric to firebase migration for crashlytics
  • How to build a Fat Framework that includes Mac Catalyst?
  • iOS universal framework compiler version changes after pod install
  • Creating extension for Notification.Name
  • Global Loading Icon Swift
  • SwiftUI - Action sheet with no title, Alert.Button using View instead of Text
  • Ionic iOS 13.2 Bug, App crash - kill() returned unexpected error
  • How to differentiate between headers and static text in iOS 13 with XCTest UI Tests
  • change the background colour of a textfield in swiftUI with xcode11.1
  • Problem creating an .IPA from VS 2019 in macOS Catalina
  • Adding Associated Domains Entitlement For a Flutter App
  • App store app uploading failed with ERROR ITMS-90534 and WARNING ITMS-90703
  • SwiftUI Unable to resize Image
  • Xcode 11 XCUITest Failed to get matching snapshots: Error getting main window kAXErrorServerNotFound
  • How to use SwiftMessage cocoapod into my application using Swift?
  • Module compiled with Swift 5.1 cannot be imported by the Swift 5.1.2 compiler (couchbaselite) xcode 11.2
  • SwiftUI observable object not updating UI
  • How to check if Apple Music is installed on the user's device?
  • Change UIAlertViewController Tint Color
  • Google Advance Native Ad Display issue
  • How to add shadow to SwiftUI arc?
  • Why is SwiftUI picker in form repositioning after navigation?
  • UIScrollView delegate methods not called when UICollectionViewCompositionalLayout is set
  • how to get list of available ios simulators?
  • react-native-orientation in iOS
  • Will apple reject my app if i force light mode on my app?
  • 'AppDelegate' is only available in iOS 13.0 or newer
  • SwiftUI - Environment Object Not Updating UI
  • How to add an Avatar image in GetStream iOS Activity Feed component?
  • How to Sign Out of Apple After Being Authenticated
  • How do you change the app icon color depending on in-app user preferences?
  • How to play MIDI with AudioKit's new AKSequencer
  • Xcode 11.2.1 Crashes When Opening a Project
  • Cannot add constraints on a fresh custom view in Xcode 11.x (.xib file)
  • inApp purchase PENDING in Purchase history
  • How to make transformation of value for binding or state
  • List of iOS font names
  • Can you tell me how to reduce flag size in the left view of textfield in the kizitonwose/CountryPickerView(github)
  • Weird behaviour of Xcode 11 Debugger - Showing values as nil when there's a value
  • How to handle failure cases of JSON response using Codable?
  • Swift segmented control and UITableView
  • Unsupported URL Swift 5
  • swift parse json - The data couldn’t be read because it isn’t in the correct format
  • Open a new window in Mac Catalyst
  • iOS 13 webaudio is totally broken for html audio elements within a webview
  • Mapbox: add annotation only if the annotation is visible on screen
  • shadow
    Privacy Policy - Terms - Contact Us © 35dp-dentalpractice.co.uk