C#嵌入dll到资源释放的问题

14 篇文章 0 订阅

        有些程序运行的时候,可能调用外部的dll,用户使用时可能会不小心丢失这些dll,导致程序无法正常运行,因此可以考虑将这些dll嵌入到资源中,启动时自动释放。对于托管的dll,我们可以用打包软件合成一个exe(例如利用Imerge),但是对于一些用C++等写的非托管dll,就比较麻烦。在这种情况下,大家可以考虑本文介绍的方法。

       1、将需要用到的dll文件嵌入资源文件中。

        (1)将需要用到的dll文件拷贝到工程中;

       (2)修改“生成操作”为“嵌入的资源”;




      这样就完成了dll文件嵌入资源的过程。

      2、编写自动释放的过程

        void ReleaseDLL()
        {
            byte[] byDll = global::命名空间.Properties.Resources.test;//获取嵌入dll文件的字节数组
            string strPath = Application.StartupPath + @"\test.dll";//设置释放路径
            //创建dll文件(覆盖模式)
            using (FileStream fs = new FileStream(strPath, FileMode.Create))
            {
                fs.Write(byDll, 0, byDll.Length);
            }
        }

       在程序启动时,首先调用上面的函数完成dll文件的释放,然后程序就能够正常运行了。这种做法只是笔者在实际项目中有时采用的一种方式,相信对大家也有一定的参考价值。

  • 2
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
C#嵌入DLL并调用其中的函数,可以使用DllImport属性和LoadLibrary函数。 以下是实现的步骤: 1. 创建一个C#项目, 添加一个类,并引入System.Runtime.InteropServices命名空间。 2. 使用DllImport属性声明要调用的DLL和其中的函数。例如: ```csharp [DllImport("user32.dll")] public static extern int MessageBox(IntPtr hWnd, string text, string caption, int options); ``` 3. 在代码中使用该函数。例如: ```csharp MessageBox(IntPtr.Zero, "Hello World!", "Greeting", 0); ``` 4. 如果要嵌入DLL,可以使用LoadLibrary函数加载DLL,并获取其中的函数地址。例如: ```csharp IntPtr handle = LoadLibrary("mydll.dll"); IntPtr funcPtr = GetProcAddress(handle, "myfunc"); ``` 5. 然后可以使用Marshal.GetDelegateForFunctionPointer方法将函数地址转换为委托类型,并使用该委托调用函数。 完整代码示例: ```csharp using System; using System.Runtime.InteropServices; class Program { [DllImport("user32.dll")] public static extern int MessageBox(IntPtr hWnd, string text, string caption, int options); [DllImport("mydll.dll")] public static extern int myfunc(int arg); [DllImport("kernel32.dll")] public static extern IntPtr LoadLibrary(string path); [DllImport("kernel32.dll")] public static extern IntPtr GetProcAddress(IntPtr handle, string symbol); static void Main() { MessageBox(IntPtr.Zero, "Hello World!", "Greeting", 0); IntPtr handle = LoadLibrary("mydll.dll"); IntPtr funcPtr = GetProcAddress(handle, "myfunc"); var myFunc = Marshal.GetDelegateForFunctionPointer<myfuncDelegate>(funcPtr); int result = myFunc(42); Console.WriteLine($"Result: {result}"); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] delegate int myfuncDelegate(int arg); } ```
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值