Plug-ins (ie dynamically loading code)?

Is there any way to implement dynamically-loadable code modules in Swift? Ideally, I'd be able to implement a protocol or subclass, and have that implementation loaded dynamically by the running host program.

Even more ideally, I'd be able to do that on both macOS and Linux.

Is this possible yet?

3 Likes

I wonder if you can use @_dynamicReplacement to achieve this. See How does the hot-reloading work in XCode11? - #5 by Arnold

I actually double this question as I'm working on a game, and would love to use some form of scripts for skills/items logic, so that I could update them on the fly without rebooting the server

If Swift code is compiled to a loadable format, dlopen will work with that format and Foundation's NSClassFromString(_:) will let you access top-level classes inside it. The easiest way for that to match up with what's in your host program is for both the main app and the plugin to compile against a common framework that contains the base class or protocol; then you can cast the result of NSClassFromString to that type.

2 Likes

Does that mean it has to be an @objc class, or derive from NSObject?

No, it just has to be top-level, non-generic, and non-private. You can use the "MyPluginModule.MainClass" syntax with it.

EDIT: Citation. (Note the comment about mangled names not being stable; that's still true on non-Apple platforms!)

2 Likes