开发者

Executing a method from a non-reference dll based on its attributes

开发者 https://www.devze.com 2023-02-13 13:08 出处:网络
I have a Visual Studio 2008 C# .NET 3.5 project where I accept a non-reference DLL as a plugin. The plugin implements an arbitrary number of classes derived from a known interface. Each class implemen

I have a Visual Studio 2008 C# .NET 3.5 project where I accept a non-reference DLL as a plugin. The plugin implements an arbitrary number of classes derived from a known interface. Each class implements a set of known functions from that interface, but may also implement unknown functions that have a known attribute.

[AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
public class SomeAttribute : Attribute
{
    public SomeAttribute(string description) { /*...*/ }
}

public class PluginClassA : IPluginInterface
{
    public PluginClassA(int some_val) : base(some_val)
    {
    }

    public override void Begin() { /*do interesting things...*/ }
    public override void End() { /*do interesting things...*/ }

    [SomeAttribute("Attribute Title")]
    public void SomeUnknownFunction() { /*do interesting things...*/ }

    [SomeAttribute("Attribute Title")]
    public void SomeOtherFunction() { /*do interesting things...*/ }
}

I'd like to be able to Load that plugin DLL and execute its functions in this order:

  1. Begin()
  2. Each function with the attribute SomeAttribute
  3. End()

I have something like this:

static void Ma开发者_如何学Goin(string[] args)
{
    Assembly u = Assembly.LoadFile("Plugin.dll");
    foreach (Type t in u.GetTypes())
    {
        if (t.GetInterface("IPluginInterface") != null)
        {
            IPluginInterface plugin = (IPluginInterface)Activator.CreateInstance(t, new int());
            plugin.Begin();

            foreach (MemberInfo mi in t.GetMembers())
            {
                if (mi.IsDefined(typeof(SomeAttribute), true))
                {
                    // we found a member with the `SomeAttribute` attribute.
                    // how can I execute that method?
                    // I'd need something like a C++ function pointer to the function.
                }
            }

            plugin.End();
        }
    }
}

Thanks, PaulH


Once you have a MethodInfo, you can use Invoke on that. If the MemberInfo returned from GetMembers actually points to a method, you can cast it to MethodInfo. So you can use this code once you have the member info:

var method = mi as MethodInfo;
if (method != null) 
    method.Invoke(plugin, null);

You can also create a delegate that represents the method. This is more suitable if you need to call it more than once.

Action action = (Action) Delegate.CreateDelegate(typeof(Action), plugin, method);
// Calls the method pointed to by the MethodInfo 
action();
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号