Is there a way to do 2-way linking?

tcak tcak at pcak.com
Wed Feb 5 09:09:29 PST 2014


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

I think Jeroen is asking for the opposite of this as library will 
call host's functions.


More information about the Digitalmars-d mailing list