【问题标题】:PlugIn function implementation with C#用C#实现插件功能
【发布时间】:2010-12-17 17:13:21
【问题描述】:

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

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

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

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

添加

这是插件代码,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);
    }
}

【问题讨论】:

  • 了解反射,动态 dll 加载
  • 这些 *.dll 文件是 .NET 程序集还是本机库?
  • 根据插件实现,没有与 GetMethod() 一起使用的方法“Abc”。
  • PlugIn 类应该是公开的。如果没有修饰符,默认情况下它声称是内部的。
  • @peo:没错。我改变了它。谢谢。

标签: c# reflection plugins


【解决方案1】:

它可以在 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

【讨论】:

【解决方案2】:
* 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了解更多详情

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-09
    • 2010-11-11
    相关资源
    最近更新 更多