✅ `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
maybe it could work because dlls are lazy loaded?
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.
yes
i dont know of any other eay
afaik its either that or
LoadLibrary
yeah, it's LoadLibrary, or Assembly.Load, or whatever the unmanaged equivalent APIs are
you probably want https://learn.microsoft.com/en-us/dotnet/api/system.runtime.interopservices.nativelibrary.setdllimportresolver?view=net-7.0
NativeLibrary.SetDllImportResolver(Assembly, DllImportResolver) Met...
Sets a callback for resolving native library imports from an assembly.
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
oh thats cool
im not going to remember it when i need it
omg I love you. i'll try this tomorrow
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.Thanks guys, the
NativeLibrary.SetDllImportResolver
worked perfectly