Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loading DLL in 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 load this dll from other C# application externally. How can I do this?

like image 775
Ahmed M. Taher Avatar asked Dec 17 '22 04:12

Ahmed M. Taher


1 Answers

Do you mean you want 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

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

like image 89
Ry- Avatar answered Jan 04 '23 14:01

Ry-