Using a C function in Objective-C (for iPhone)

我的未来我决定 提交于 2019-12-06 04:23:05

Here's en example of how it would be used:

int nCoords = 4;
float vertexXCoords[n] = {0.0, 0.0, 20.0, 20.0};
float vertexYCoords[n] = {0.0, 20.0, 20.0, 0.0};
NSPoint testPoint = NSMakePoint(5, 10);

BOOL testPointIsInPoly = pnpoly(nCoords, xCoords, yCoords, testPoint.x, testPoint.y);

Note that there's nothing specific to Objective-C in here. This is C code (though it does use the Cocoa BOOL and NSPoint C types). Since Objective-C is a strict superset of C, any valid C code is also valid Objective-C. This is also a case in which Objective-C's unique features would not be particularly useful. (Numerical calculations in general are less complex and more readable in plain C.)

You can just call it. Objective-C is just a front-end to a C API and a way of re-writing methods as functions (to some approximation, anyway...) so you can call a C function just as you would in C code.

- (int)doWhatever {
  // ...
  int hitTest = pnPoly(/*blah*/);
  return hitTest;
}

You can use C primitive types like int and float in Objective-C without issue, too. So call the function with floats :). If you need to store such values in Foundation collection classes like NSArray, then you can wrap them in a class called NSNumber.

NSNumber *someFloat = [NSNumber numberWithFloat: f];
float usefulValue = [someFloat floatValue];

objective C is a superset of C, so you can call C routines. If you are calling that routine a lot, inline it or make it a macro.

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