开发者

How to call a Managed DLL File in C#?

开发者 https://www.devze.com 2023-03-22 19:38 出处:网络
I am makin开发者_如何学JAVAg a scripting language but I havea 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#.

I am makin开发者_如何学JAVAg 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)


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...


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());
}


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消