[英]How to declare type in an Imported or Embed Resource DLL
我实际上正在寻找将所有DLL和EXE合并到单个文件中的解决方案。
我在这里问了一个问题:
我收到了可以将DLL作为嵌入资源进行链接的建议,然后将嵌入的DLL文件写入内存并使用DLLImport导入DLL。
我按照这里的说明操作:
以下就是我所做的:
[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
属性用于从非托管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);
希望有所帮助。
如果你想在一个文件中填充托管程序集和exe,我建议你看一下ILMerge 。
它比使用资源手动操作更容易使用。
DllImport
仅适用于本机DLL。
嵌入托管DLL时,您有几种选择:
要么
要么
AssemblyResolve
处理程序,该处理程序在运行时从资源中读取并将所需的DLL返回到.NET运行时... 在使用此类Assembly中的类型时,请参见以下链接(它们包括参考资料和一些示例代码等):
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.