使用C#实现PlugIn功能

时间:2010-12-17 17:13:21

标签: c# reflection plugins

我需要调用一个函数来用C#调用用户的dll。

例如,当用户使用类ABC生成abc.dll时,我想加载dll以在类中运行方法xyz(a)。

object plugInObject = node.GetPlugInObject("abc.dll", "ABC");
plugInObject.runMethod("xyz", "a");

如何在C#中实现这些功能?

ADDED

这是插件代码,dll被复制为plugin / plugin.dll。

namespace HIR
{
    public class PlugIn
    {
        public int Add(int x, int y)
        {
            return (x + y);
        }
    }
}

这是调用此插件的那个。

using System;
using System.Reflection;

class UsePlugIn
{
    public static void Main() 
    {
        Assembly asm = Assembly.LoadFile("./plugin/plugin.dll");
        Type plugInType = asm.GetType("HIR.PlugIn");
        Object plugInObj = Activator.CreateInstance(plugInType);

        var res = plugInType.GetMethod("Add").Invoke(plugInObj, new Object[] { 10, 20 });
        Console.WriteLine(res);
    }
}

2 个答案:

答案 0 :(得分:2)

它可以在C#和.NET中翻译成以下内容:

Assembly asm = Assembly.LoadFile("ABC.dll");
Type plugInType = asm.GetType("ABC");
Object plugInObj = Activator.CreateInstance(plugInType);

plugInType.GetMethod("xyz").Invoke(plugInObj, new Object[] { "a" });

它被称为Reflection

答案 1 :(得分:0)

* Declare the method with the static and extern C# keywords.
* Attach the DllImport attribute to the method. The DllImport attribute allows you to specify the name of the DLL that contains the method. The common practice is to name the C# method the same as the exported method, but you can also use a different name for the C# method.
* Optionally, specify custom marshaling information for the method's parameters and return value, which will override the .NET Framework default marshaling.

//Example of how to use methods from User32.dll
[DllImport("User32.dll", SetLastError=true)]
static extern Boolean MessageBeep(UInt32 beepType);

see了解更多详情