嵌入C ++库到.NET库 [英] Embed C++ Libraries into .Net Libraries

查看:128
本文介绍了嵌入C ++库到.NET库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的.NET程序集,我将不得不使用一些本地(C ++)的dll。通常我们需要将C ++的dll复制到bin文件夹,并使用的PInvoke 来调用它。为了节省配送成本,我想C ++的嵌入到我的NET的DLL直接,使分布式组件的数量会少些。

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?

推荐答案

您会嵌入您的本机DLL的资源。

You would embed your native DLLs as resources.

然后在运行时,你将不得不提取那些本机DLL到临时文件夹;你不一定要在应用程序文件夹的写权限,当你的应用程序启动:认为Windows Vista或Windows 7和UAC。因此,你可以使用这种代码从一个特定的路径加载它们:

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);
    }
  }
}

这篇关于嵌入C ++库到.NET库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆