如何使用对Objective-C的非托管引用来移植Swift代码

时间:2018-08-20 09:02:12

标签: objective-c swift porting

我试图将以下Swift代码移植到Objective-C:

var contextImage: UIImage? = ... 
let image: CGImage? = contextImage?.cgImage
let dataProvider: CGDataProvider? = image?.dataProvider
let data: CFData? = dataProvider?.data
let baseAddress = CFDataGetBytePtr(data!)
contextImage = nil

let unmanagedData = Unmanaged<CFData>.passRetained(data!)
var pixelBuffer: CVPixelBuffer?
let status = CVPixelBufferCreateWithBytes(nil, 
                (image?.width)!, 
                (image?.height)!, 
                kCVPixelFormatType_32BGRA, 
                UnsafeMutableRawPointer( mutating: baseAddress!),
                (image?.bytesPerRow)!, 
                { releaseContext, baseAddress in
                    let contextData = Unmanaged<CFData>.fromOpaque(releaseContext!)
                    contextData.release()
                }, 
                unmanagedData.toOpaque(), 
                nil, 
                &pixelBuffer)

但是我陷入了Unmanaged部分,无法在ARC下找到正确的Objective-C方法(Unmanaged的{​​{3}}仅存在于Swift):

CGImageRef image = contextImage.CGImage;
CGDataProviderRef dataProvider = CGImageGetDataProvider(image);
CFDataRef data = CGDataProviderCopyData(dataProvider);
const UInt8 * baseAddress = CFDataGetBytePtr(data);
contextImage = nil;

// ... now what?

最终,我通过将Swift文件集成到Objective-C项目中来实现了这一目标,但我仍然想知道,将原始Swift代码移植到Objective-C中的正确方法是什么?

1 个答案:

答案 0 :(得分:0)

我认为您不需要不受管理。即使在Swift文档中也使用此功能RawPointers。 这就是ObjC的文档外观。

CVReturn CVPixelBufferCreateWithBytes (CFAllocatorRef allocator,
size_t width,
size_t height,
OSType pixelFormatType,
void *baseAddress,
size_t bytesPerRow,
CVPixelBufferReleaseBytesCallback releaseCallback,
void *releaseRefCon,
CFDictionaryRef pixelBufferAttributes,
CVPixelBufferRef *pixelBufferOut);

其实现可能看起来像这样。

CVPixelBufferRef pixelBuffer = NULL;
cvErr = CVPixelBufferCreateWithBytes(kCFAllocatorDefault,
FRAME_WIDTH,
FRAME_HEIGHT,
kCVPixelFormatType_32BGRA,
(void*)CFDataGetBytePtr(imageData),
CGImageGetBytesPerRow(image),
NULL,
NULL,
NULL,
&pixelBuffer);

CVPixelBufferCreate的更多文档。