I am loading a c++ assembly in my Dotnet core 3.1 application.
If I use DllImport, I can load and use the assembly as expected.
[DllImport(
"lib/mylibrary.dll",
CallingConvention = CallingConvention.Cdecl,
EntryPoint = "MyEndpoint"
)]
However, I want to select the appropriate library for the platform, windows or linux. I tried loading the DLL dynamically using System.Reflection.Assembly.LoadFrom
but this gives the error Bad IL Format
.
I have tried a few different ways, but all give the same error
// read bytes
var bytes = File.ReadAllBytes("lib/myLibrary.dll");
var assembly = System.Reflection.Assembly.Load(bytes); //bad IL format
// Load From
var assembly = System.Reflection.Assembly.LoadFrom("lib/myLibrary.dll"); //bad IL format
//Load from assembly path
var assembly = System.Runtime.Loader.AssemblyLoadContext.Default.LoadFromAssemblyPath("lib/myLibrary.dll"); //bad IL format
//From embedded resource
var stream = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("my-library.manifestname.dll");
var assembly System.Runtime.Loader.AssemblyLoadContext.Default.LoadFromStream(stream); //bad IL format
What am I doing wrong here?
EDIT:
solution:
static class MyWrapper
{
static MyWrapper {
// The linked solution suggests setting the dll path using kernel32, this only works for windows. Set Environment.CurrentDirectory instead.
if(RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
Environment.CurrentDirectory = "lib/windows";
}
else
{
Environment.CurrentDirectory = "lib/unix";
}
}
...
[DllImport(
"my_library", //IMPORTANT: drop the extension to preserve compatibility between dylib, dll, so, etc.
CallingConvention = CallingConvention.Cdecl,
EntryPoint = "MyEntryPoint"
)]
}