ScotMac
ScotMac

Reputation: 21

Dynamically load native embedded dll from C++/CLI (clr based) project/dll

I have a C# Managed library (dll) that is calling into a C++/CLI (w/ /clr) library, in order to call some native library functions.

What i want to do is embed the native dll's in the C++/CLI libary/dll (in order to make a simply one library entity), and then dynamically load them (the native dll's).

I have been able to successfully embed them into the C++/CLI library, but i have no idea how to then use that data to dynamically load them. I tried using (AssemblyResolve and Assembly.Load), but i don't get a chance to use it before the attempted load of the C++/CLI libary returns "Could not load file or assembly" error.

I have read about the assembly initializer (appears a bit like dllmain). Do i need to set one up that then loads the embedded assemblies?

UPDATE:I have written up the code below to PULL the DLL out of the "resource" and dump it into a file, and that appears to be working fine.

{
  Assembly ^ CurrentAssembly = Assembly::GetExecutingAssembly();

  array<String^> ^ ResourceNames = CurrentAssembly->GetManifestResourceNames();

  String^ BaseDir = AppDomain::CurrentDomain->BaseDirectory;

  for (int i = 0; i < ResourceNames->Length; i++)
  {
    if ( ResourceNames[i]->EndsWith(".dll") )
    {
      Stream^ stream = CurrentAssembly->GetManifestResourceStream(ResourceNames[i]);

      if ( stream != nullptr )
      {
        array<Byte^> ^ assemblyData = gcnew array<Byte^>(stream->Length);

        FileStream^ fileStream = File::Create(BaseDir + ResourceNames[i]);
        stream->CopyTo(fileStream);
        fileStream->Close();
      }
    }
  }
}

Upvotes: 1

Views: 2996

Answers (1)

Igor Skochinsky
Igor Skochinsky

Reputation: 25318

The Win32 API does not support loading native DLLs from memory. You need to have the file on disk to be able to use it. Assembly.Load and friends only support managed DLLs (aka assemblies).

So you'll have to extract the DLL to a temporary location, then use LoadLibrary and GetProcAdress to use its APIs.

Here's a post describing how to do it: http://blogs.msdn.com/b/jonathanswift/archive/2006/10/03/dynamically-calling-an-unmanaged-dll-from-.net-_2800_c_23002900_.aspx

Upvotes: 2

Related Questions