Install D:
or GCC version:sudo apt-get install dmd
Compile:sudo apt-get install gdc
or with GCC version:dmd main.d -L-ldl -ofmaind
Run:gdc main.d -ldl -o maind
./maind
If the install command above doesn't work fo you, you can go to the D download site and get DMD from there.
import std.stdio;
import core.sys.posix.dlfcn;
// Convenient aliases
alias int function(int, int) ADD;
alias void function(const char *) PRINTME;
int main()
{
// Load library
auto lib = dlopen("./libhello.so".ptr, RTLD_LAZY);
// Verify success
if (!(lib is null))
{
// Locate add and, if found, call it
auto Add = cast(ADD)dlsym(lib, "add");
if (Add is null)
writeln("Can't find add.");
else
writeln("The result is: ", Add(1, 2));
// Locate printme and, if found, call it
auto PrintMe = cast(PRINTME)dlsym(lib, "printme");
if (PrintMe is null)
writeln("Can't find printme.");
else
PrintMe("Hello from D!");
// Clean up
dlclose(lib);
}
else
{
writeln("Can't load ./libhello.so");
return 1;
}
return 0;
}
Output:
The result is: 3 Hello from library: Hello from D!