On Wednesday, 5 February 2014 at 17:39:34 UTC, Benjamin Thaut wrote:
Am 05.02.2014 18:33, schrieb Jeroen Bollen:
On Wednesday, 5 February 2014 at 16:27:10 UTC, Benjamin Thaut wrote:
Am 05.02.2014 16:36, schrieb Jeroen Bollen:
On Wednesday, 5 February 2014 at 13:52:10 UTC, Benjamin Thaut wrote:
Am 05.02.2014 14:21, schrieb Jeroen Bollen:
Is it possible to load in a dynamic library in D, and have the library you just loaded call your own functions? Imagine having a plugin
loader
and the plugins call methods like 'addButton()' from the host
application.

Yes, thats what core.runtime.loadLibrary is for.
http://dlang.org/phobos/core_runtime.html#.Runtime.loadLibrary

You can also always fall back to operating system functions like,
LoadLibrary and GetProcAddress for windows.

Kind Regards
Benjamin Thaut

How exactly does that work 2 ways? Can I just define the functions and
not implement them in the library?

You don't define functions, just function pointers. You could also do
it oop style:

// The loader
import core.sys.windows.windows;

interface IPlugin
{
 void pluginMethod1();
 void pluginMethod2();
}

// function pointer definition for the entry function
extern(C) alias IPlugin function() pluginEntry;

IPlugin loadPlugin(const(char)[] path)
{
 auto handle = cast(HMODULE)runtime.loadLibrary(path);
 //use dlsym on linux
 auto entry = cast(pluginEntry)GetProcAddress(handle,
"pluginEntry".ptr);
 return entry(); // get the plugin interface
}


// The plugin
interface IPlugin
{
 void pluginMethod1();
 void pluginMethod2();
}

class PluginImpl : IPlugin
{
 override void pluginMethod1() { ... }
 override void pluginMethod2() { ... }
}

export extern(C) IPlugin pluginEntry()
{
 return new PluginImpl();
}

This however will have issues on windows, because the runtime is not shared. On Linux it should work just fine if you remember to link
against the shared runtime.

You might also want to watch this talk from D-conf 2013:
http://dconf.org/2013/talks/nowak.html

Kind Regards
Benjamin Thaut

That example seems to only let the loader call the plugin, and not the
other way around.

Well as I already said, for the other way around just pass function-pointers / interfaces to the plugin as soon as you established the one-way connection.

Ah so like an initialize function taking a set of arguments representing functions and classes?

Reply via email to