linking and using a C++ library with an Objective-C application

本秂侑毒 提交于 2019-12-03 13:16:10

You're going to hit one obstacle in the form of what's called "name mangling". C++ stores function names in a way not compatible with Obj-C.

Objective-C doesn't implement classes in the same way as C++, so it's not going to like it.

One way around this is to implement a set of simple C functions which call the C++ functions. It'll be a good challenge to keep the number of C functions as low as possible! You'll end up with a nice compact interface! :)

To declare these functions in a C++ file, you'll need to mark them as C with:

extern "C" int function_name(char *blob,int number, double foo) {...}

This disables the standard name-mangling.

Build a header file with the prototypes for all these functions that you can share with your objective C code.

You won't be able to pass classes around in the same way (because your ObjC code can't use them), but you'll be able to pass pointers (although you might have to lie about the types a little).

Most of the projects I work on have an ObjC frontend and C++ backend. If you're dealing exclusively with functions, then Dave Gamble's name mangle fix is correct, but if you're dealing with more complex situations, where you need to deal with both ObjC and C++ objects, your best bet is to wrap the C++ objects in ObjC objects. Using opaque references (which is a very fancy way of saying void*), you can actually hand around C++ objects in ObjC and vice versa. I have some sample code that may be helpful.

That said, for graphics you're probably going to take a serious performance hit doing custom C++ rather than using Core Image and the related frameworks. Core Image and the other graphics frameworks are highly optimized for the Mac, and you're very unlikely to do better with hand-rolled C++ (or even very well-written C++ that isn't specifically for the Mac). As you move to 10.6 and grand central dispatch, the performance difference is going to be even more notable because you'll lose all the parallelization advances that you would get for free otherwise. This has nothing to do with ObjC; Core Image is C. You can call it from C++ all you like. I just recommend against custom graphics processing on Mac in any language unless you need portability or you have the expertise necessary to beat Core Image.

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