Issue with CoreText CTFrameGetLineOrigins in Swift

柔情痞子 提交于 2019-12-18 07:10:16

问题


I have the following code working in Objective-C

NSArray *lines = (NSArray *)CTFrameGetLines((__bridge CTFrameRef)columnFrame);
CGPoint origins[[lines count]];
CTFrameGetLineOrigins((__bridge CTFrameRef)columnFrame, CFRangeMake(0, 0), origins);

But when ported to Swift, the compiler complains with a Cannot convert the expression´s ´Void´to type ´CMutablePointer<CGPoint> in the CTFrameGetLineOrigins line

let nsLinesArray: NSArray = CTFrameGetLines(ctFrame) // Use NSArray to bridge to Array
let ctLinesArray = nsLinesArray as Array
var originsArray: Array<CGPoint> = CGPoint[]()
//var originsArray: NSMutableArray = NSMutableArray.array()
let range: CFRange = CFRangeMake(0, 0)
CTFrameGetLineOrigins(ctFrame, range, originsArray)

I had to use NSArray in the CGFrameGetLines function, and then convert to a Swift Array, and inspecting the ctLinesArray, shows that the CTLine objects are retrieved correctly

I tried using NSMutableArray for the originsArray, with the same result.

Any idea of what is missing?


回答1:


You have to add the address-of operator & to pass the pointer to the start of the originsArray to the function:

CTFrameGetLineOrigins(ctFrame, range, &originsArray)

Reference: Interacting with C APIs in the "Using Swift with Cocoa and Objective-C" book:

C Mutable Pointers

When a function is declared as taking a CMutablePointer<Type> argument, it can accept any of the following:

  • ...
  • An in-out Type[] value, which is passed as a pointer to the start of the array, and lifetime-extended for the duration of the call.

And from Expressions in "The Swift Programming Language" book:

In addition to the standard library operators listed above, you use & immediately before the name of a variable that’s being passed as an in-out argument to a function call expression.

An addition (as @eharo2 already figured out), the originsArray must have room for the necessary number of elements, which can be achieved with

var originsArray = CGPoint[](count:ctLinesArray.count, repeatedValue: CGPointZero)


来源:https://stackoverflow.com/questions/24434853/issue-with-coretext-ctframegetlineorigins-in-swift

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!