how to import a class from dll?

15,398

Solution 1

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.

Solution 2

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);
    }
}
Share:
15,398
Okan Kocyigit
Author by

Okan Kocyigit

https://bitbucket.org/ocanal/ https://github.com/okankocyigit Email: hasanokan[at]gmail[dot]com

Updated on June 29, 2022

Comments

  • Okan Kocyigit
    Okan Kocyigit almost 2 years

    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?

  • Okan Kocyigit
    Okan Kocyigit about 13 years
    No I want to add dll while program running, not with add reference option, so how can I create a unmanaged dll?
  • Darin Dimitrov
    Darin Dimitrov about 13 years
    @ocanal, you could load an assembly at runtime using Reflection and the Assembly.LoadFrom method. Once the assembly is loaded you could list all the types inside and invoke methods on them.