Wednesday, March 7, 2018 [Tweets] [Favorites]

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

Stay up-to-date by subscribing to the Comments RSS Feed for this post.

Leave a Comment