Loading a DLL into an external program?

I have a C # ClassLibrary that contains a function to sum two numbers:

namespace ClassLibrary1 { public class Calculator { public int Calc(int i, int b) { return i + b; } } } 

I want to download this DLL from another C # application from the outside. How can i do this?

+4
source share
4 answers

Do you want you to load it dynamically by file name? Then yes, you can use the Assembly.LoadFile method as follows:

 // Load the assembly Assembly a = Assembly.LoadFile(@"C:\Path\To\Your\DLL.dll"); // Load the type and create an instance Type t = a.GetType("ClassLibrary1.Calculator"); object instance = a.CreateInstance("ClassLibrary1.Calculator"); // Call the method MethodInfo m = t.GetMethod("Calc"); m.Invoke(instance, new object[] {}); // Get the result here 

(The translated example is from here , but I wrote it, so don't worry!)

+12
source

Just based on a response to minitech. If you can use C # 4.0, you can omit some reflection calls.

  public static void Main() { Assembly ass = Assembly.LoadFile(@"PathToLibrar\ClassLibraryTest.dll"); var type = ass.GetType("ClassLibrary1.Calculator"); dynamic instance = Activator.CreateInstance(type); int add = instance.Calc(1, 3); } 

Here, as an instance type dynamic , you don't need to look for the Calc method by reflection.

But the best way is to define the interface upstream

  public interface ICalculator { int Calc(int i, int b); } 

and implement it in its class downstream

 public class Calculator : ICalculator { public int Calc(int i, int b) { return i + b; } } 

Then you can do the reflection minimally to build the object.

  public static void Main() { Assembly ass = Assembly.LoadFile(@"PathToLibrar\ClassLibraryTest.dll"); var type = ass.GetType("ClassLibrary1.Calculator"); ICalculator instance = Activator.CreateInstance(type) as ICalculator; int add = instance.Calc(1, 3); } 

This will give you better performance.

+2
source

Right-click on the links in the project explorer in Visual Studio and just select the assembly. Then you can use it:

 using ClassLibrary1; class Program { static void Main() { Calculator calc = new Calculator(); int result = calc.Cal(1, 2); } } 
-one
source

If you are using visual studio, you can reference this DLL in your project and not include the namespace in the new source code

-one
source

Source: https://habr.com/ru/post/1392094/


All Articles