C#C
C#3y ago
swagrid

✅ `DllImport` on a dll name only known at runtime

I have a bunch of native dlls that have the same interface (they export the same functions with identical signatures).

My managed library knows at startup which of these dlls it has to load, but it doesn't know it at compile time, so I cannot hardcode the file name like [DllImport("LibA.dll")]. I'm not talking about the dlls being in different directories. All binaries are in the same folder, but I have to selectively load the dll depending on how the managed part is started. I know I could use LoadLibrary and GetProcAdress to import the native dll dynamically, but I'd rather not do all the manual work if I don't have to.

Is there a way to load a native dll and map it to a C# class or interface with the native dll only being known at runtime?
Was this page helpful?