Monday, July 15, 2013

Create API by Loading DLLs at Runtime

Creating a plugin API can be difficult, especially if you don't know where to start.  I think the easiest way to do it is to iterate through DLL files in a plugins folder and load them dynamically.  Start by creating a class library that defines what a plugin will look like (probably with interfaces).  Distribute this library to potential plugin developers and reference it in your application.  Get an instance of each plugin by doing this for each file in your plugins directory (for C#, but Java probably has an equivalent):

Assembly assembly = Assembly.LoadFrom(plugindir + file + ".dll");
Type type = assembly.GetType(file);
Object pluginInstance = Activator.CreateInstance(type);

Cast pluginInstance to an implementer of your plugin interface.  Once you have loaded all the plugins, you can call some method on each one every time some modifiable behavior starts to execute.  I recommend something similar to Forge's event bus.

Also, cactus cat.

No comments:

Post a Comment