C
C#2y 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?
10 Replies
sibber
sibber2y ago
maybe it could work because dlls are lazy loaded?
swagrid
swagridOP2y ago
I thought about this, but that would mean I'd have to have a specific C# class per dll, and all of these classes are identical except for the dll path. I want to avoid that.
sibber
sibber2y ago
yes i dont know of any other eay afaik its either that or LoadLibrary
JakenVeina
JakenVeina2y ago
yeah, it's LoadLibrary, or Assembly.Load, or whatever the unmanaged equivalent APIs are
reflectronic
reflectronic2y ago
it will allow you to control what library is loaded, given the name you specified in dllimport you can use NativeLibrary.Load to do the actual loading in the implementation of the resolver
sibber
sibber2y ago
oh thats cool im not going to remember it when i need it
swagrid
swagridOP2y ago
omg I love you. i'll try this tomorrow
Accord
Accord2y ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.
swagrid
swagridOP2y ago
Thanks guys, the NativeLibrary.SetDllImportResolver worked perfectly
Want results from more Discord servers?
Add your server