Wednesday, March 7, 2018

Getting the Current NSBundle

Nicolas Bouilleaud:

  1. Use backtrace() to find the function pointer of the caller;
  2. Use dladdr() to find the executable image path containing this function;
  3. Find the loaded bundle with this executable path.

[…]

With this, I can finally write Bundle.current everywhere, instead of Bundle.main or Bundle(for: AnyClass).

Update (2018-03-12): Leo Natan:

Very cool, but this is an error prone approach due to inlining and optimizations.

For performance, __builtin_frame_address()/__builtin_return_address() either directly in Swift if possible or in a C shim function would work quite well. Same risks as original approach.

Comments RSS · Twitter

Leave a Comment