3
votes

mydll.dll

namespace mydll
{
    public class MyClass {
        public static int Add(int x, int y)
        {
            return x +y;
        }
    }
}

In another project how can I import MyClass or just Add function?

I want to add with DllImport,

[DllImport("mydll.dll", CharSet = CharSet.Auto) ] public static extern .......

how can I do that?

3
Are you using C# on both sides of the application (class definition and class consumer)? If you are, there might be a better waySWeko

3 Answers

3
votes

You can use Reflection to load assembly at runtime.

Here a piece of code you can use :

Assembly myAssembly ;
myAssembly = Assembly.LoadFile("myDll.dll");

object o;
Type myType =  myAssembly.GetType("<assembly>.<class>");
o = Activator.CreateInstance(myType);

Here you can find a good tutorial.

6
votes

DllImport is used to call unmanaged code. The MyClass class you have shown is managed code and in order to call it in another assembly you simply add reference to the assembly containing it and invoke the method. For example:

using System;
using mydll;

class Program
{
    static void Main()
    {
        int result = MyClass.Add(1, 3);
        Console.WriteLine(result);
    }
}
0
votes

If both sides are .NET, you still need some common interface (or use dynamic). If you have that in place, you can use Reflection or the ComponentModel.