Pointers 在swift中将CFContextRef转换为可变的空指针?
我正在尝试将此objc代码转换为swift:Pointers 在swift中将CFContextRef转换为可变的空指针?,pointers,types,casting,swift,void,Pointers,Types,Casting,Swift,Void,我正在尝试将此objc代码转换为swift: CGContextRef contextRef = CGBitmapContextCreate(NULL, proposedRect.size.width, proposedRect.size.height,
CGContextRef contextRef = CGBitmapContextCreate(NULL,
proposedRect.size.width,
proposedRect.size.height,
CGImageGetBitsPerComponent(imageRef),
0,
colorSpaceRef,
(CGBitmapInfo)kCGImageAlphaPremultipliedFirst);
NSGraphicsContext *context = [NSGraphicsContext graphicsContextWithGraphicsPort:contextRef flipped:NO];
到目前为止,我的结论是:
var bitmapContext: CGContext = CGBitmapContextCreate(data, UInt(proposedRect.width), UInt(proposedRect.height), CGImageGetBitsPerComponent(image), 0, colorSpace, CGBitmapInfo(CGImageAlphaInfo.PremultipliedFirst.toRaw()))
let context = NSGraphicsContext(graphicsPort: bitmapContext, flipped: false)
问题是CGBitmapContextCreate
返回CGContext
类型,而NSGraphicsContext
初始值设定项接受graphicsPort
作为CMutableVoidPointer
类型。那么如何将CGContext
转换为CMutableVoidPointer
相关的反向类型铸造在这里找到,但它并没有提供太多的帮助给我
此处的文档:
声明如下:
当函数声明为采用CMutableVoidPointer参数时,
对于任何类型,它都可以接受与CMutablePointer相同的操作数
类型
由此看来,它应该是这样工作的:
var p: CMutablePointer<CGContext> = &bitmapContext
NSGraphicsContext *context = [NSGraphicsContext graphicsContextWithGraphicsPort:p flipped:NO];
var p:CMutablePointer=&bitmapContext
NSGraphicsContext*上下文=[NSGraphicsContext GraphicsContextWithGraphicsSport:p翻转:否];
实际上,您应该能够将&bitmapContext
直接传递到CMutableVoidPointer
参数
Swift没有C意义上的“指针”。我最后使用了
reinterpretCast
函数返回bitmapContext
地址的中间Int
变量
var bitmapContext: CGContext = CGBitmapContextCreate(...)
let bitmapContextAddress: Int = reinterpretCast(bitmapContext)
let bitmapContextPointer: CMutableVoidPointer = COpaquePointer(UnsafePointer<CGContext>(bitmapContextAddress))
let context = NSGraphicsContext(graphicsPort: bitmapContextPointer, flipped: false)
var bitmapContext:CGContext=CGBitmapContextCreate(…)
让bitmapContextAddress:Int=reinterpretCast(bitmapContext)
让bitmapContextPointer:CMutableVoidPointer=COpaquePointer(非安全指针(bitmapContextAddress))
let context=NSGraphicsContext(GraphicsSport:bitmapContextPointer,翻转:false)
传递&contextRef
有效吗?无效&contextRef
有CGContextRef*
类型,这不是我需要的。基本上我需要简单的castCGContextRef
,因为void*
原始类型CGContextRef
已经是一个指针了。因此,在objc中,我能够进行简单的强制转换void*pointer=CGBitmapContextCreate(…)
,并获得所需的内容。在swift中,bitmapContext
是指向指针void**
的指针,而它并不完全是NSGraphicsContext
接受的graphicsPort
argument@chebur这是Swift,不是C,不是C++,不是Objc。Swift中没有指针的概念。如果您不接受或不理解这一点,您将无法获得Swift。您试图建议的是通过执行&bitmapContext
来获取指向CGContextRef
的指针。但是这意味着函数需要的正是CGContextRef
值,该值简单地向下转换为CMutableVoidPointer
(void*
,用C表示),而不是像您前面所说的那样指向CGContextRef
。同样,您是用C表示。在Swift中,&
不是一个引用运算符,从ObjC到Swift的桥接处理在内部传递不透明类型。i、 e.&bitmapContext
不会创建指向CGContextRef
的指针。Swift中没有指针这类东西。Swift提供。里面有一些例子说明了&
的正确用法。到目前为止,&
的意思是获取一个值的引用谢谢你的回答!不过,我认为,reinterpretCast
已经从语言中消失了;您需要改为使用unsafeBitCast
。当然,您是对的,但NSGraphicsContext的对象初始值设定项已更改其签名,因此不再需要位转换