Skip to content

Instantly share code, notes, and snippets.

@lorepozo
Last active October 24, 2020 12:48
Show Gist options
  • Save lorepozo/5fd4913ef50408e064d7 to your computer and use it in GitHub Desktop.
Save lorepozo/5fd4913ef50408e064d7 to your computer and use it in GitHub Desktop.
cocoa button with Golang callback
#include <Cocoa/Cocoa.h>
extern void ButtonClick(void);
@interface GoPasser : NSObject
+ (void)buttonClick:(id)sender; // this should call the cgo function defined in main.go
@end
void StartApp(void);
#include "c.h"
@implementation GoPasser
+ (void)buttonClick:(id)sender{
ButtonClick(); // this should call the cgo function defined in main.go
}
@end
// GoPasser's buttonClick: gets called in here
void StartApp(void){
[NSAutoreleasePool new];
[NSApplication sharedApplication];
[NSApp setActivationPolicy:NSApplicationActivationPolicyRegular];
id menubar = [[NSMenu new] autorelease];
id appMenuItem = [[NSMenuItem new] autorelease];
[menubar addItem:appMenuItem];
[NSApp setMainMenu:menubar];
id appMenu = [[NSMenu new] autorelease];
id appName = [[NSProcessInfo processInfo] processName];
id quitTitle = [@"Quit " stringByAppendingString:appName];
id quitMenuItem = [[[NSMenuItem alloc] initWithTitle:quitTitle
action:@selector(terminate:) keyEquivalent:@"q"]
autorelease];
[appMenu addItem:quitMenuItem];
[appMenuItem setSubmenu:appMenu];
NSRect buttonFrame = NSMakeRect(59, 33, 82, 32);
NSButton *button = [[NSButton alloc] initWithFrame:buttonFrame];
button.bezelStyle = NSRoundedBezelStyle;
button.title = @"Click Me!";
[button setTarget:[GoPasser class]];
[button setAction:@selector(buttonClick:)];
NSWindow *window = [[NSWindow alloc] initWithContentRect:NSMakeRect(0, 0, 200, 100)
styleMask:NSTitledWindowMask backing:NSBackingStoreBuffered defer:NO];
[window cascadeTopLeftFromPoint:NSMakePoint(20,20)];
[window setTitle:appName];
[window makeKeyAndOrderFront:nil];
[window.contentView addSubview:button];
[NSApp activateIgnoringOtherApps:YES];
[NSApp run];
return;
}
# command-line-arguments
duplicate symbol _StartApp in:
    $WORK/command-line-arguments/_obj/_cgo_export.o
    $WORK/command-line-arguments/_obj/main.cgo2.o
duplicate symbol _OBJC_METACLASS_$_GoPasser in:
    $WORK/command-line-arguments/_obj/_cgo_export.o
    $WORK/command-line-arguments/_obj/main.cgo2.o
duplicate symbol _OBJC_CLASS_$_GoPasser in:
    $WORK/command-line-arguments/_obj/_cgo_export.o
    $WORK/command-line-arguments/_obj/main.cgo2.o
ld: 3 duplicate symbols for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
package main
/*
#cgo CFLAGS: -x objective-c
#cgo LDFLAGS: -framework Cocoa
#include "c.m"
*/
import "C"
import "fmt"
//export ButtonClick
func ButtonClick() {
fmt.Println("Button Click!")
}
func main() {
C.StartApp()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment