In-source way to call any C Library

Andrej Mitrovic andrej.mitrovich at gmail.com
Fri Mar 18 13:15:35 PDT 2011


For runtime linking with DLLs, you're looking for LoadLibrary,
GetProcAddress and friends. They're in core.sys.windows.windows.

The static constructor is useful if you want to have C functions in
module scope. Personally, I wrap C libraries in classes and hide all
the loading details there.

However the following is what I think you're after:
module testDllLoad;

import std.stdio;
import std.string;
import std.path : join, curdir;
import core.sys.windows.windows;
import std.exception;

extern(C) int function() MyTestResult;

static this()
{
    string dllFileName = join(r"..\Debug\", "CLibTest.dll");
    HMODULE dllModule;
    enforce(dllModule = LoadLibraryA(toStringz(dllFileName)));
    enforce(MyTestResult = GetProcAddress(dllModule, "_MyTestResult"));
}

void CSUsingCLib()
{
    int result = MyTestResult();  // use it
    writeln(result);
}

void main()
{
    CSUsingCLib();
}

I've tested this with a C DLL which exports the function
_MyTestResult. The DLL was located in the previous directory, under
Debug, just like your example. It worked fine.

Btw, in case you don't know, its very important to specify the calling
convention and the /correct/ calling convention for a function. For a
C DLL this is always extern(C).


More information about the Digitalmars-d-learn mailing list