Hi, I am new to programming, I got work to remove warnings and errors thrown by swiftLint. I have resolved most of the warnings but I am stuck at one place.
let ptrOptions = UnsafeMutablePointer(&Options)
Where Options is a struture.
it is saying that it might result in a dangling pointer. How I can remove thsi?
warning: initialization of 'UnsafeMutablePointer<Options>' results in a dangling pointer
let ptrOptions = UnsafeMutablePointer(&options)
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
note: implicit argument conversion from 'Options' to 'UnsafeMutablePointer<Options>' produces a pointer valid only for the duration of the call to 'init(_:)'
let ptrOptions = UnsafeMutablePointer(&options)
^~~~~~~~
note: use 'withUnsafeMutablePointer' in order to explicitly convert argument to pointer valid for a defined scope
let ptrOptions = UnsafeMutablePointer(&options)
^
it suggest a solution, which is withUnsafeMutablePointer
withUnsafeMutableBytes(of: &options) { ptrOptions in
...
}
be aware that the ptrOptions is valid only inside the closure.
It would help us to help you if you provided a little more info on your goals. Can you post a small snippet that illustrates the problem you’re having?
withUnsafeMutableBytes(of: &optionArray) { (ptrOption) -> Void in
do {
var return = try lib.function(v1: &v1.access, v2: &ptrOption, v3: &v3, v4: v4.count)
}catch{
print("Error")
}
}
Compiler is throwing dangling pointer warning , i want to remove that dangling pointer warning.
i have to pass pointer (ptrOption) to function lib.function
variable optionArray is array of C obj
What @eskimo and I are trying to get at is "what is lib.function, specifically?". The correct solution depends on that information. For instance, suppose lib.function were something like the following:
In a case like this, you wouldn't be able to return (or use) the result outside of the closure scoped to withUnsafeMutableBytes, because the pointer options contained in the C struct would not be valid outside of that scope.
Thanks @eskimo , i am able to remove some dangling pointer warning after reading about Ampersand . Thank you for sharing link of The Peril of the Ampersand
lib -> lib is a struct in swift module
function -> is a method/function inside swift module structure (lib)
function does the following task :
Open .dylib file of Clibaray
Load Sym of the function
Call C library function
Return Response of that function
var optionvar = Options()
var optionArray = [optionvar] //Trying to create array
var return = try lib.function(v1: &v1.access, v2: &optionArray, v3: &v3, v4: v4.count)
When i am trying to pass optionArray it is throwing error .
Cannot convert [optionvar] to UnsafeMutablePointer<[Options]>
It’s hard to say what’s going on here without more details. However, I took the code you posted and turned it into a minimal example and that works just fine: