6

In my .Net assemblies I would have to make use of some native (C++ ) dlls. Usually we need to copy the C++ dlls into the bin folder and use PInvoke to call it. To save the distribution cost, I want to embed the C++ into my .Net dll direct, so that the number of assemblies distributed would be less.

Any idea how to do this?

Gregory Pakosz
  • 69,011
  • 20
  • 139
  • 164
Graviton
  • 81,782
  • 146
  • 424
  • 602
  • possible duplicate of [Embedding unmanaged dll into a managed C# dll](http://stackoverflow.com/questions/666799/embedding-unmanaged-dll-into-a-managed-c-dll) – Darin Dimitrov Jul 31 '10 at 09:18
  • 1
    i disagree with closing as duplicate -- the answers for the other question describe the "embed as resources" part but not how to properly load the libraries once they have been extracted to the drive – Gregory Pakosz Jul 31 '10 at 09:32

2 Answers2

4

You would embed your native DLLs as resources.

Then at runtime, you would have to extract those native DLLs into a temporary folder; you don't necessarily have write access to the application folder when your application launches: think windows vista or windows 7 and UAC. As a consequence, you would use this kind of code to load them from a specific path:

public static class NativeMethods {

  [DllImport("kernel32")]
  private unsafe static extern void* LoadLibrary(string dllname);

  [DllImport("kernel32")]
  private unsafe static extern void FreeLibrary(void* handle);

  private sealed unsafe class LibraryUnloader
  {
    internal LibraryUnloader(void* handle)
    {
      this.handle = handle;
    }

    ~LibraryUnloader()
    {
      if (handle != null)
        FreeLibrary(handle);
    }

    private void* handle;

  } // LibraryUnloader


  private static readonly LibraryUnloader unloader;

  static NativeMethods()
  {
    string path;

    // set the path according to some logic
    path = "somewhere/in/a/temporary/directory/Foo.dll";    

    unsafe
    {
      void* handle = LoadLibrary(path);

      if (handle == null)
        throw new DllNotFoundException("unable to find the native Foo library: " + path);

      unloader = new LibraryUnloader(handle);
    }
  }
}
Gregory Pakosz
  • 69,011
  • 20
  • 139
  • 164
0

You can embed your dlls as resources.

At runtime, extract them to the same folder as your exe and use P/Invoke to call methods inside them.

logicnp
  • 5,796
  • 1
  • 28
  • 32
  • you don't necessarily have write access to the application folder when your application launches: think windows vista or windows 7 and UAC – Gregory Pakosz Aug 02 '10 at 09:01