Skip to content

Instantly share code, notes, and snippets.

@miguelmartin75
Last active May 10, 2025 20:00
Show Gist options
  • Save miguelmartin75/4baa89cbd5cf96da049d77f16b32c990 to your computer and use it in GitHub Desktop.
Save miguelmartin75/4baa89cbd5cf96da049d77f16b32c990 to your computer and use it in GitHub Desktop.
Example of Nim with Objective-C, issue: https://github.com/nim-lang/Nim/issues/9492. Compile with `nim withArc` to execute using Objective-C's ARC and `nim withoutArc` to depend on Nim's ARC to call release
--outdir:"build"
--nimcache:"build/cache"
when defined(useObjcArc):
--passC:"-fobjc-arc"
else:
--passC:"-fno-objc-arc"
task withArc, "compile and run with arc":
exec "nim objc --listCmd -d:useObjcArc -r guts.nim"
task withoutArc, "compile and run with arc":
exec "nim objc --listCmd -r guts.nim"
#import <Foundation/Foundation.h>
@interface Greeter: NSObject
{
}
- (void)greet:(long)x y:(long)dummy;
@end
#include "guts.h"
// #import <Cocoa/Cocoa.h> // not needed, Foundation.h is already included
#include <stdio.h>
@implementation Greeter
- (void)greet:(long)x y:(long)dummy
{
printf("Hello, World!\n");
}
- (void)dealloc {
printf("dealloc is called\n");
#if ! __has_feature(objc_arc)
printf("super dealloc - arc is not enabled\n");
fflush(stdout);
[super dealloc];
#endif
}
@end
{.compile:("guts.m", "-fobj-c").}
type Id {.importc: "id", header: "<Foundation/Foundation.h>", final.} = distinct int
proc release(id: Id) {.importobjc: "release", header: "<Foundation/Foundation.h>".}
proc `=destroy`(id: Id) =
when not defined(useObjcArc):
id.release()
proc newGreeter: Id {.importobjc: "Greeter new", nodecl, header: "guts.h".}
proc greet(self: Id, x, y: int) {.importobjc: "greet", nodecl, header: "guts.h".}
# NOTE:
# I am calling the wrapped code in `foo` due Objective-C ARC, as `dealloc` isn't called in main scope.
# Nim's ARC works in main scope. It doesn't matter either way (macOS will release memory on process
# exit), but this is done for demonstration purposes.
proc foo =
var g = newGreeter()
g.greet(12, 34)
foo()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment