IT박스

Objective-C 대신 Cocoa와 함께 C ++를 사용 하시겠습니까?

itboxs 2020. 7. 11. 11:09
반응형

Objective-C 대신 Cocoa와 함께 C ++를 사용 하시겠습니까?


Apple은 Carbon 64 비트를 지원하지 않기 때문에 C ++ 및 Cocoa 프레임 워크를 사용하는 응용 프로그램을 작성하고 싶습니다. C ++은 리눅스와 Windows에서 구현할 때 꽤 바닐라처럼 보이지만 Mac OS X에서는 Obj-C 래퍼와 같은 추가 Apple 특정 코드 조각이 필요한 것처럼 보입니다. 또한 애플은 개발자가 C ++ 대신 Objective-C로 작성하도록 강요하고 있지만, 내가 틀릴 수도 있습니다.

크로스 플랫폼을 유지하기 쉬운 Mac에서 코드를 작성하는 경로를 찾으려고합니다. Linux / Windows 용 C ++로 코드를 작성하고 Objective-C에서 많은 부분을 다시 작성하는 것은 매우 비효율적입니다.

미래에 지원되고 Xcode에서 지원 될 C ++로 코드를 작성하는 방법이 있습니까? 또한 이것이 가능하다면 X 코드에서 C ++과 Objective-C를 어떻게 혼합합니까? 감사.


Cocoa 애플리케이션을 C ++로 완전히 작성할 수는 없습니다. Cocoa는 Key-Value Bindings, 델리게이트 (Cocoa 스타일) 및 대상 동작 패턴과 같은 많은 핵심 기술에 Objective-C의 후기 바인딩 기능에 크게 의존합니다. 늦은 바인딩 요구 사항으로 인해 C ++ ⁱ와 같은 컴파일 타임 바운드 형식의 언어로 Cocoa API를 구현하기가 매우 어렵습니다. 물론 OS X에서 실행되는 순수한 C ++ 앱을 작성할 수 있습니다. Cocoa API는 사용할 수 없습니다.

따라서 다른 플랫폼의 C ++ 앱과 Cocoa 기반 애플리케이션간에 코드를 공유하려는 경우 두 가지 옵션이 있습니다. 첫 번째는 C ++로 모델 레이어를 작성하고 Cocoa로 GUI를 작성하는 것입니다. 이것은 Mathematica를 포함하여 매우 큰 일부 앱에서 사용하는 일반적인 접근 방식 입니다. C ++ 코드는 변경되지 않은 상태로 둘 수 있습니다 (OS X에서 C ++를 쓰거나 컴파일하기 위해 "펑키"애플 확장이 필요하지 않음). 컨트롤러 계층은 Objective-C ++ (아마도 "펑키 한"Apple 확장명)를 사용합니다. Objective-C ++는 C의 수퍼 셋 인 것처럼 Objective-C ++는 C ++의 수퍼 셋입니다. Objective-C ++에서는 [some-objc-object callMethod];C ++ 함수 내에서 호출 (예 :)을 전달하는 objc 스타일 메시지를 만들 수 있습니다 . 반대로 ObjC 코드 내에서 다음과 같이 C ++ 함수를 호출 할 수 있습니다.

@interface MyClass {
    MyCPPClass *cppInstance;
}
@end

@implementation MyClass
- (id)init {
    if(self = [super init]) {
        cppInstance = new MyCPPClass();
    }
    return self;
}
- (void) dealloc {
    if(cppInstance != NULL) delete cppInstance;
    [super dealloc];
}
- (void)callCpp {
    cppInstance->SomeMethod();
}
@end

Objective-C 언어 안내서 에서 Objective-C ++에 대한 자세한 정보를 찾을 수 있습니다 . 뷰 레이어는 순수한 Objective-C가 될 수 있습니다.

두 번째 옵션은 크로스 플랫폼 C ++ 툴킷을 사용하는 것입니다. Qt는툴킷이 청구서에 적합 할 수 있습니다. 크로스 플랫폼 툴킷은 일반적으로 Mac 사용자가 모든 모양과 느낌의 세부 정보를 정확하게 얻지 못하고 Mac 사용자는 Mac 응용 프로그램의 UI에서 세련되기를 기대하기 때문에 멸시됩니다. Qt는 놀랍게도 훌륭한 작업을 수행하지만 대상과 앱 사용에 따라 충분할 수 있습니다. 또한 Qt API에는 대략적인 대체 기능이 있지만 Core Animation 및 일부 QuickTime 기능과 같은 일부 OS X 관련 기술을 잃게됩니다. 지적했듯이 Carbon은 64 비트로 이식되지 않습니다. Qt는 Carbon API에서 구현되므로 Trolltech / Nokia는 64 비트 호환을 위해 Qt를 Cocoa API로 이식해야했습니다. 내 이해는 Qt의 다음 릴리스 (현재 출시 후보))는이 전환을 완료하고 OS X에서 64 비트와 호환됩니다. C ++과 Cocoa API 통합에 관심이있는 경우 Qt 4.5의 소스를 살펴볼 수 있습니다.


Apple 잠시 동안 Apple은 Cocoa API를 Java에서 사용할 수있게했지만 브리지는 광범위한 수동 조정이 필요했으며 위에서 설명한 Key-Value Bindings와 같은 고급 기술을 처리 할 수 ​​없었습니다. 현재 Python, Ruby 등과 같이 동적으로 유형이 지정된 런타임 바운드 언어는 Objective-C없이 Cocoa 앱을 작성하는 유일한 옵션입니다 (물론 이러한 브리지는 Objective-C를 사용합니다).


음, 어리석게 들릴지 모르지만 실제로는 Mac OS X 용 GUI를 만들기 위해 순수한 C ++ 코드를 작성할 수 있지만 Cocoa 프레임 워크와 연결해야합니다.

/*
 * test1.cpp
 * This program shows how to access Cocoa GUI from pure C/C++
 * and build a truly functional GUI application (although very simple).
 * 
 * Compile using:
 *   g++ -framework Cocoa -o test1 test1.cpp
 *
 * that will output 'test1' binary.
 */


#include <CoreFoundation/CoreFoundation.h>
#include <objc/objc.h>
#include <objc/objc-runtime.h>
#include <iostream>

extern "C" int NSRunAlertPanel(CFStringRef strTitle, CFStringRef strMsg,
                               CFStringRef strButton1, CFStringRef strButton2, 
                               CFStringRef strButton3, ...);


int main(int argc, char** argv)
{
    id app = NULL;
    id pool = (id)objc_getClass("NSAutoreleasePool");
    if (!pool)
    {
        std::cerr << "Unable to get NSAutoreleasePool!\nAborting\n";
        return -1;
    }
    pool = objc_msgSend(pool, sel_registerName("alloc"));
    if (!pool)
    {
        std::cerr << "Unable to create NSAutoreleasePool...\nAborting...\n";
        return -1;
    }
    pool = objc_msgSend(pool, sel_registerName("init"));

    app = objc_msgSend((id)objc_getClass("NSApplication"),
                       sel_registerName("sharedApplication"));

    NSRunAlertPanel(CFSTR("Testing"),
                    CFSTR("This is a simple test to display NSAlertPanel."),
                    CFSTR("OK"), NULL, NULL);

    objc_msgSend(pool, sel_registerName("release"));
    return 0;
}

Yes, you can just use C++ (i.e. writing it in *.cpp files) and even mix C++ and Objective-C inside *.mm files (standard Objective-C code is stored in *.m files).

Of course, you still have to use Objective-C for your user-interface and create Objective-C wrappers for your C++ objects. Another option is to switch to Qt which is a C++ Framework that supports Windows, Mac OS X, and Linux -- and will be released under the LGPL with the next version 4.5.


Yes you can mix them.

You need to use Objective-C to directly operate on your GUI objects and receive notifications from them.

These Objective-C objects can directly call C++ logic if you put them in .mm files, instead of the pure Objective-C .m files. Note that you may see (much) older advice suggesting using an uppercase .M to indicate Objective-C++ but this is very flaky and likely to confuse you as well as the compiler.

You don't need to wrap each and every C++ object but your Objective-C code will need to contain pointers to them.

Apple no longer publish any samples showing how to do this.

There's a great video by Peter Steinberger hosted at Realm [Objective] C++: What Could Possibly Go Wrong? I highly recommend for anyone still using Objective-C++ and you can quickly skim the transcript.


If you're just looking to use plain vanilla C++, this is absolutely supported and really no different than any other platform. Xcode even has a template for it under File > New Project > Command Line Utility > C++ Tool. Also, a number of the popular open-source libraries (libcurl, libxml2, sqlite, etc) come with OS X and are available for dynamic linking. You don't have to use Cocoa or anything Apple-specific if you don't want to.

If you do want to use Cocoa in certain portions of your app, take a look at Objective-C++. You can mix C++ and Objective-C in the same file by giving it an extension of .mm, or by right-clicking on the file in Xcode and selecting Get Info > General then changing the File Type to sourcecode.cpp.objcpp. The second option is useful if you have a .cpp file where you want to use Objective-C within a Mac-specific #ifdef.


Though this is years old question...

I have tried to make C++ wrapper of some Cocoa classes.

It was pretty nice experience. C++ provided better type safety than Objective-C, and made me to write less code. But compile time and memory safety are worse. It is possible but some dynamic based features were not easy to handle. I think it doesn't make sense to deal with it on C++.

Anyway my project was finally abandoned due to announcement of Swift. It cleared all the reasons I wanted to use C++ at first, and provides even more and better.


If you're writing a purely graphical application, i.e. you're drawing everything using code, consider openFrameworks. It's an opensource graphical programming languages built on top of C/C++. It has addons which allow people to extend the language. They have an addon for the iphone. I believe that it comes with the library and the XCode projects that will help you compile apps for the iPhone and iPod touch.

참고URL : https://stackoverflow.com/questions/525609/use-c-with-cocoa-instead-of-objective-c

반응형