C#加载原生dll动态简单

时间:2014-04-18 14:19:30

标签: c# class oop dynamic dll

所以我不知道该怎么做......

我有一个程序“Prg.cs”和一个dll“Test.dll”。 我试过了:

Assembly asm=Assembly.Load(@"C:\Users\Me\documents\visual studio 2013\Projects\Prg\Prg\bin\Debug\Test.dll");
Type runApp = asm.GetType();
dynamic thisApp = Activator.CreateInstance(runApp, this);

但是给我错误:

    An unhandled exception of type 'System.IO.FileLoadException' occurred in mscorlib.dll

Additional information: Could not load file or assembly 'C:\\Users\\Me\\documents\\visual studio 2013\\Projects\\Prg\\Prg\\bin\\Debug\\Test.dll' or one of its dependencies. The given assembly name or codebase was invalid. (Exception from HRESULT: 0x80131047)

谢谢!

1 个答案:

答案 0 :(得分:0)

您可以这样做:

class Program
{
  static void Main(string[] args)
  {
    var dll = Assembly.LoadFile(@"C:\Test.dll");//The path of your dll

    var theType = dll.GetType("dll.Test");
    var c = Activator.CreateInstance(theType);
    var method = theType.GetMethod("Output");//Your method in the class
    method.Invoke(c, new object[]{@"Hello world"});

    Console.ReadLine();
  }
}

此链接可以帮助您stackoverflow.com/a/18362515/3383479