1

I am working on a mixed project of swift and objective-c. I need to use a function like this.

+ (nullable NSString *)funcName:(NSString **)param;

In swift,the param becomes AutoreleasingUnsafeMutablePointer type.

Tried code like this

let str : NSString = ""
let pointer = UnsafeMutablePointer(mutating: str.utf8String)
let unsafe = AutoreleasingUnsafeMutablePointer<NSString?>.init(pointer)
let str = funcName(str.utf8String)

But it results in crash because the pointer I sent in is pointing to nil

1 Answer 1

1

This

let str : NSString = ""
let pointer = UnsafeMutablePointer(mutating: str.utf8String)

is already undefined behavior: You are creating a mutable pointer referencing the same memory as the (immutable) str.utf8String.

Actually it is much simpler: You can pass the address of an optional NSString as inout argument with &.

var param: NSString?
let result = YourObjCClass.funcName(&param)

The compiler automatically does the necessary conversion. There is seldom a need to create an AutoreleasingUnsafeMutablePointer explicitly.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.