这主要是一个“学术”问题,所以请不要问“你为什么需要这样做”:-)
我有这个 objective-c 方法,我没有使用 ARC(我知道如果我不释放分配的字符串它会泄漏)。 此方法采用指向内存中某物的指针,然后将指向的内容更改为 NSMutableString。
+(void) writeString:(void **)var
{
NSMutableString *aString = [[NSMutableString alloc] initWithFormat:@"pippo %@", @"pluto"];
*var = aString;
}
在 Objective C 中,我以这种方式访问它并且它工作正常
NSString *str;
[FLSwiftUtils writeString:&str];
NSLog(@"%@", str); // prints pippo pluto
现在我想以同样的方式从 Swift 访问它,但我对指针有疑问。 我试过这种方式:
var opaque = COpaquePointer.null() // create a new opaque pointer pointing to null
FLSwiftUtils.writeString(&opaque)
println(opaque)
但它打印 VSs14COpaquePointer(有 1 个 child ),因为 opaque
是一个指针,我不明白如何推导它并访问指向的 NSMutableString
如果我尝试从不透明值开始创建一个 UnsafePointer:
var str = UnsafePointer<NSMutableString>(opaque)
println(str)
println 打印一个空行
我什至试过这个:
var secondStr = AutoreleasingUnsafePointer<NSMutableString>(opaque.value)
println(secondStr)
println(secondStr.memory)
但它打印
VSs26AutoreleasingUnsafePointer(有 1 个 child ) __NSCF字符串
我想我已经接近解决方案了,但我肯定做错了什么。
最佳答案
我在 Apple 论坛上收到了答案(注意:此代码是 FOR ARC)
+ (void)writeString:(void **)var
{
NSMutableString *aString = [[NSMutableString alloc] initWithFormat:@"pippo %@", @"pluto"]; // this is autoreleased by ARC
*var = (void *)CFBridgingRetain(aString); // send a retain, the release will be sent at the swift side
}
然后像这样将它发布到 Swift 中:
var opaque = COpaquePointer.null() // create a new opaque pointer pointing to null
TestClass.writeString(&opaque)
var string = Unmanaged<NSString>.fromOpaque(opaque).takeRetainedValue() // this function: creates an object, from the opaque pointer "opaque", take it's value and balance it with a release
println(string)
关于objective-c - 使用 **void 参数从 swift 访问 objective-c 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24080991/