简体   繁体   English

如何从dll导入一个类?

[英]how to import a class from dll?

mydll.dll 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? 在另一个项目中,如何导入MyClass或只添加功能?

I want to add with DllImport , 我想用DllImport添加,

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

how can I do that? 我怎样才能做到这一点?

DllImport is used to call unmanaged code. DllImport用于调用非托管代码。 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. 您显示的MyClass类是托管代码,为了在另一个程序集中调用它,您只需添加对包含它的程序集的引用并调用该方法。 For example: 例如:

using System;
using mydll;

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

You can use Reflection to load assembly at runtime. 您可以使用Reflection在运行时加载程序集。

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. 在这里你可以找到一个很好的教程。

If both sides are .NET, you still need some common interface (or use dynamic). 如果双方都是.NET,您仍然需要一些通用接口(或使用动态)。 If you have that in place, you can use Reflection or the ComponentModel. 如果已安装,则可以使用Reflection或ComponentModel。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM