I just released ObjectiveC.jl 0.1, a package for working with Objective-C in Julia. The package was created by @MikeInnes back in 2014, but wasn’t registered, or functional anymore on recent versions of Julia. That has been fixed, and you can use ObjectiveC.jl to interface with Objective-C frameworks using Julia 1.6 - 1.10, although for now only macOS is supported.
Demo
The core feature of the package is the ability to call Objective-C methods from Julia, and to build a Julia type hierarchy that matches Objective-C. For example, you can create an Objective-C NSString object, and then call methods on it:
julia> using ObjectiveC
# create a wrapper class that will hold an object pointer
julia> @objcwrapper NSString
# call a NSString class method to create an NSString object
julia> str = NSString(@objc [NSString stringWithUTF8String:"test"::Ptr{Cchar}]::id{NSString})
NSStringInstance (object of type NSTaggedPointerString)
# call an instance method to get back the contents of our NSString
julia> unsafe_string(@objc [str::id{NSString} UTF8String]::Ptr{Cchar})
"test"
# or, easier, you can have ObjectiveC.jl generate property methods
julia> @objcproperties NSString begin
@autoproperty UTF8String::Ptr{Cchar}
end
julia> unsafe_string(str.UTF8String)
"test"
For more examples, see the README. ObjectiveC.jl also provides a Foundation submodule that already contains definitions for NSString and a few other essential types:
julia> NSArray([str,str])
(
test,
test
)
julia> length(ans)
2
# etc
People familiar with Objective-C might note that the @objc
call syntax almost looks like native Objective-C, with the exception of type information (e.g. id{NSString}
). This is for performance reasons, as it allows us to generate fully static code that performs reasonably well:
julia> @benchmark @objc [$str::id{NSString} UTF8String]::Ptr{Cchar}
BenchmarkTools.Trial: 10000 samples with 985 evaluations.
Range (min … max): 57.360 ns … 1.825 μs ┊ GC (min … max): 0.00% … 0.00%
Time (median): 62.903 ns ┊ GC (median): 0.00%
Time (mean ± σ): 65.431 ns ± 34.296 ns ┊ GC (mean ± σ): 0.00% ± 0.00%
▂▄▆▅▇▇▇▆▇█▂
▂▃▄▅████████████▅▅▄▄▃▃▃▃▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▁▂▂▂▁▂▂▂▂▂▂▂▂▂▂▂ ▄
57.4 ns Histogram: frequency by time 88.8 ns <
Memory estimate: 0 bytes, allocs estimate: 0.
There’s a couple of more advanced features, like @objcblock
to generate callable blocks for Julia functions, but those are also demonstrated in the README.
Current status
As the package has recently been revamped, APIs may still change, so it’s only at v0.1 right now. However, Metal.jl uses it for all interactions with the Metal APIs, so the functionality seems to be working pretty well.
In the process of revamping the package, some functionality also got lost, like the ability to create Objective-C classes from Julia. I personally don’t have a need for that, so if you’re interested, PRs to reinstate that functionality are most welcome