Load D shared library on windows x64
Tofu Ninja
joeyemmons at yahoo.com
Fri Aug 17 20:20:49 UTC 2018
Do shared libraries work? I am trying to load a D library into a
D program but Runtime.loadLibrary just returns null for me and I
am not sure what I am doing wrong.
import std.stdio;
import std.file : exists, getcwd, rename;
import core.thread;
import std.conv : to;
version(tofu_dynamic){
import core.sys.windows.windows;
import core.runtime;
pragma(msg, "Dynamic Link Library");
HINSTANCE g_hInst;
export extern (Windows) BOOL DllMain(HINSTANCE hInstance, ULONG
ulReason, LPVOID pvReserved) {
switch (ulReason) {
case DLL_PROCESS_ATTACH:
writeln("DLL_PROCESS_ATTACH");
Runtime.initialize();
break;
case DLL_PROCESS_DETACH:
writeln("DLL_PROCESS_DETACH");
Runtime.terminate();
break;
case DLL_THREAD_ATTACH:
writeln("DLL_THREAD_ATTACH");
return false;
case DLL_THREAD_DETACH:
writeln("DLL_THREAD_DETACH");
return false;
default:
}
g_hInst = hInstance;
return true;
}
pragma(mangle, "rti_start") export void rti_start(){
writeln("rti start :)");
}
} else {
void main(string[] args) {
uint id = 0;
while(true) {
if(exists("graph.dll")){
auto name = "rti." ~ id.to!string ~ ".dll";
rename("graph.dll", name);
id++;
loadLib(name);
}
Thread.sleep(dur!("seconds")(1));
}
}
static void loadLib(string dllName) {
import core.sys.windows.windows;
import core.runtime;
Thread.sleep(dur!("seconds")(1));
writeln("Start Dynamic Link to ", dllName, "...");
HMODULE h = cast(HMODULE) Runtime.loadLibrary(dllName);
if (h is null) {
writeln("error loading");
return;
}
scope(exit){
if (!Runtime.unloadLibrary(h))
writeln("error freeing dll");
}
FARPROC fp = GetProcAddress(h, "rti_start");
if (fp is null) {
writeln("error loading symbol rti_start");
return;
}
auto fun = cast(void function()) fp;
fun();
writeln("End...");
}
}
More information about the Digitalmars-d-learn
mailing list