【问题标题】:How to declare type in an Imported or Embed Resource DLL如何在导入或嵌入资源 DLL 中声明类型
【发布时间】:2012-02-11 11:07:43
【问题描述】:

我实际上正在寻找将所有 DLL 和 EXE 合并到单个文件中的解决方案。

我在这里问了一个问题:

How to use an DLL load from Embed Resource?

我收到建议我可以将 DLL 链接为嵌入资源,然后将嵌入的 DLL 文件写入内存并使用 DLLImport 导入 DLL。

我按照这里的说明进行操作:

http://weblogs.asp.net/ralfw/archive/2007/02/04/single-assembly-deployment-of-managed-and-unmanaged-code.aspx

以下是我所做的:

[DllImport("System.Data.SQLite.dll")]
public static SQLiteConnection sqLiteConnection1 = new SQLiteConnection();

public Form1()
{
    ResourceExtractor.ExtractResourceToFile("MyApp.System.Data.SQLite.dll", "System.Data.SQLite.dll");
}

public static class ResourceExtractor
{
    public static void ExtractResourceToFile(string resourceName, string filename)
    {
        if (!System.IO.File.Exists(filename))
        using (System.IO.Stream s = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName))
        using (System.IO.FileStream fs = new System.IO.FileStream(filename, System.IO.FileMode.Create))
        {
            byte[] b = new byte[s.Length];
            s.Read(b, 0, b.Length);
            fs.Write(b, 0, b.Length);
        }
    }
}

但是 Visual Studio 说这个块会产生错误:

[DllImport("System.Data.SQLite.dll")]
public static SQLiteConnection sqLiteConnection1 = new SQLiteConnection();

错误 1 ​​属性“DllImport”在此声明类型上无效。它仅对“方法”声明有效。

如何在该 DLL 中声明类型?

非常感谢。

【问题讨论】:

  • DllImport 仅适用于非托管代码,此处还需要一个 extern 关键字。
  • 由于您的程序在这里只使用托管代码,您关注的博客是针对不同的问题

标签: c# reflection dll embed dllimport


【解决方案1】:

DllImport 属性用于声明来自非托管 DLL 的方法。

由于System.Data.SQLite.dll 是一个托管程序集,您需要在将程序集保存到磁盘后,通过Reflection 加载它,类似于:

using System.Data;
...

var assembly = Assembly.LoadFile(@"path\to\System.Data.SQLite.dll");
var type = assembly.GetType("System.Data.SQLite.SQLiteConnection");
IDbConnection connection = (IDbConnection)Activator.CreateInstance(type);

希望对您有所帮助。

【讨论】:

    【解决方案2】:

    如果您想将托管程序集和 exe 放在一个文件中,我建议您查看 ILMerge

    使用起来比手动处理资源要容易得多。

    【讨论】:

      【解决方案3】:

      DllImport 仅适用于本机 DLL。

      在嵌入托管 DLL 时,您有多种选择:

      • 使用SmartAssembly(商业)等工具
        它可以嵌入和合并其他内容(无需更改源代码)

      • code that yourself in less than 10 lines(免费但最小的源代码更改)
        将所有需要的依赖项标记为“嵌入式资源” - 这样它们就包含在 EXE 文件中...您需要设置一个 AssemblyResolve 处理程序,该处理程序在运行时从资源中读取并将所需的 DLL 返回到 .NET 运行时...

      在使用此类程序集中的类型时,请参阅这些链接(它们包括参考资料和一些示例代码等):

      【讨论】:

        猜你喜欢
        • 2013-10-30
        • 2016-03-12
        • 1970-01-01
        • 2012-03-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多