How to call a Managed DLL File in C#?

2019-01-26 00:46发布

问题:

I am making a scripting language but I have a serious problem.

I need to make it so you can call .NET DLLs in the language but I have found no way to do this in C#.

Does any one know how can I load and call a .NET dll programmatically? (I can not just Add reference so don't say that)

回答1:

Here's how I did it:

Assembly assembly = Assembly.LoadFrom(assemblyName);
System.Type type = assembly.GetType(typeName);
Object o = Activator.CreateInstance(type);
IYourType yourObj = (o as IYourType);

where assemblyName and typeName are strings, for example:

string assemblyName = @"C:\foo\yourDLL.dll";
string typeName = "YourCompany.YourProject.YourClass";//a fully qualified type name

then you can call methods on your obj:

yourObj.DoSomething(someParameter);

Of course, what methods you can call is defined by your interface IYourType...



回答2:

You can use Assembly.LoadFrom, from there use standard reflection to get at types and methods (i assume you already do this in your scripting). The example on the MSDN page (linked) shows this:

Assembly SampleAssembly;
SampleAssembly = Assembly.LoadFrom("c:\\Sample.Assembly.dll");
// Obtain a reference to a method known to exist in assembly.
MethodInfo Method = SampleAssembly.GetTypes()[0].GetMethod("Method1");
// Obtain a reference to the parameters collection of the MethodInfo instance.
ParameterInfo[] Params = Method.GetParameters();
// Display information about method parameters.
// Param = sParam1
//   Type = System.String
//   Position = 0
//   Optional=False
foreach (ParameterInfo Param in Params)
{
    Console.WriteLine("Param=" + Param.Name.ToString());
    Console.WriteLine("  Type=" + Param.ParameterType.ToString());
    Console.WriteLine("  Position=" + Param.Position.ToString());
    Console.WriteLine("  Optional=" + Param.IsOptional.ToString());
}


回答3:

It sounds like you need to use one of the overloads of Assembly.Load (Assembly.Load at MSDN). Once you have dynamically loaded your assembly, you can use System.Reflection, dynamic objects, and/or interfaces/base classes to access types within it.