Creating window application in pure c on mac osx

前端 未结 5 1670
孤街浪徒
孤街浪徒 2020-12-24 08:33

I\'m creating an application in pure C on Mac OSX. What I want is to create window in witch my app will be stored.

Preferably I want it to be pure C solution, but if

5条回答
  •  太阳男子
    2020-12-24 08:48

    Can you do this? Yes and no (you can do anything if you're persistent enough). Yes you can, but no you shouldn't. Regardless, this can be done for the incredibly persistent among you. Since coding up an example will take awhile, I found a generous soul on the net who already did it. Look at this repository on GitHub for the full code and explanations. Here are some snippets:

    cmacs_simple_msgSend((id)objc_getClass("NSApplication"), sel_getUid("sharedApplication"));
    
    if (NSApp == NULL) {
        fprintf(stderr,"Failed to initialized NSApplication...  terminating...\n");
        return;
    }
    
    id appDelObj = cmacs_simple_msgSend((id)objc_getClass("AppDelegate"), sel_getUid("alloc"));
    appDelObj = cmacs_simple_msgSend(appDelObj, sel_getUid("init"));
    
    cmacs_void_msgSend1(NSApp, sel_getUid("setDelegate:"), appDelObj);
    cmacs_void_msgSend(NSApp, sel_getUid("run"));
    

    As you'll notice, this code uses the Objective-C runtime API to create a faux AppDelegate. And creating the window is an involved process:

    self->window = cmacs_simple_msgSend((id)objc_getClass("NSWindow"), sel_getUid("alloc"));
    
    /// Create an instance of the window.
    self->window = cmacs_window_init_msgSend(self->window, sel_getUid("initWithContentRect:styleMask:backing:defer:"), (CMRect){0,0,1024,460}, (NSTitledWindowMask | NSClosableWindowMask | NSResizableWindowMask | NSMiniaturizableWindowMask), 0, false);
    
    /// Create an instance of our view class.
    ///
    /// Relies on the view having declared a constructor that allocates a class pair for it.
    id view = cmacs_rect_msgSend1(cmacs_simple_msgSend((id)objc_getClass("View"), sel_getUid("alloc")), sel_getUid("initWithFrame:"), (CMRect){ 0, 0, 320, 480 });
    
    // here we simply add the view to the window.
    cmacs_void_msgSend1(self->window, sel_getUid("setContentView:"), view);
    cmacs_simple_msgSend(self->window, sel_getUid("becomeFirstResponder"));
    
    // Shows our window in the bottom-left hand corner of the screen.
    cmacs_void_msgSend1(self->window, sel_getUid("makeKeyAndOrderFront:"), self);
    return YES;
    

    So, yes. You can write a Cocoa app in pure C. But I wouldn't recommend it. 90% of that code can be replaced by an xib file, and doing it this way really restricts your app because more advanced features of the Apple development stack really on Objective-C features. While it's technically possible to do everything this way, you're making it much harder than it ought to be.

提交回复
热议问题