D: How would one make a shared dynamically linked D library?

Hipreme msnmancini at hotmail.com
Wed Nov 8 13:24:32 UTC 2023


On Wednesday, 8 November 2023 at 11:48:58 UTC, BoQsc wrote:
> I would like to export some functionality as external shared 
> dynamically linked D library.
>
> Is it possible to do that in D Language and what are 
> limitations?
>
> A simple `writeln` example would be great.
>
> What I expect is an executable that uses functions, variables, 
> classes, modules from compiled external shared D dynamic 
> library.
>
> Example of shared dynamic libraries depending on other shared 
> dynamic libraries would be great as well.

For a complete reference, check: 
https://wiki.dlang.org/Win32_DLLs_in_D

Create a dub project.
Set its targetType to `dynamicLibrary`.


Now, create a function:
```d
module dllmodule;

version(Windows)
{
     import core.sys.windows.dll;
     mixin SimpleDllMain;
}

export extern(C) void helloWorld()
{
     import std.stdio;
     writeln("DLL: Hello World");
}
```

Now, when you enter `dub`, you'll get a .dll on windows, and a 
.so on linux.
You can use any compiler of your preference.


Now, whenever you need to load this dll, you'll need to call:

```d
module my_app;

extern(C) void function helloWorld();

void main()
{
     import core.runtime;
     void* dllmodule = Runtime.loadLibrary("dllmodule.dll");
     version(Windows)
     {
         import core.sys.windows.dll;
         helloWorld =  
cast(typeof(helloWorld))GetProcAddress(dllmodule, "helloWorld");
     }
     else version(Posix)
     {
         import core.sys.posix.dlfcn;
         helloWorld = cast(typeof(helloWorld))dlsym(dllmodule, 
"helloWorld");
     }
     helloWorld();
}
```

With that, there it is.
You also may need to call `core.runtime.rt_init()` if you're not 
calling from D


More information about the Digitalmars-d-learn mailing list