2

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)

TheBoyan
  • 6,802
  • 3
  • 45
  • 61
Grunt
  • 173
  • 2
  • 2
  • 11

3 Answers3

5

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

scrat.squirrel
  • 3,607
  • 26
  • 31
  • It's sometimes a good idea to create a separate app domain for the loaded assembly which means you can throw it away once you're done. – Kev Jul 26 '11 at 13:59
  • How did you reference `IYourType` without referencing the DLL in the project? – Eric Omine Jun 02 '16 at 18:43
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());
}
George Duckett
  • 31,770
  • 9
  • 95
  • 162
1

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.

JohnC
  • 844
  • 4
  • 10