tags:

views:

214

answers:

1

Is there a way to dynamically load and call functions from DLLs dynamically in D? I'd like my program to be able to load plugins at startup and perhaps on-the-fly as well.

+3  A: 

It depends on how dynamic you want to get. If you want to dynamically load a dll and run some predefined functions, there is a very nice wrapper by Wei Li here. Thanks to the power of templates, it allows you to do things like these:

// define functions
alias Symbol!("MessageBoxW", int function(HWND, LPCWSTR, LPCWSTR, UINT)) mbw;
alias Symbol!("MessageBoxA", int function(HWND, LPCSTR, LPCSTR, UINT)) mba;
// load dll
auto dll = new Module!("User32.dll", mbw, mba);
// call functions
dll.MessageBoxW(null, "Hello! DLL! ", "Hello from MessageBoxW", MB_OK);
dll.MessageBoxA(null, "Hello! DLL! ", "Hello from MessageBoxA", MB_OK);

The code is D1. For D2, you have to replace char[] with string, use toStringz() and possibly remove scope.

stephan
I wish I had more mod +1 points. This is exactly what I was looking for. Thanks!
Timothy Baldridge
@Timothy: Glad it helped. To me, the code is a good example how much you can achieve with a couple of lines of code using templates and mixins. It almost feels like Python.
stephan