c# - Executing a method from a non-reference dll based on its attributes -
i have visual studio 2008 c# .net 3.5 project accept non-reference dll plugin. plugin implements arbitrary number of classes derived known interface. each class implements set of known functions interface, may implement unknown functions have 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 able load plugin dll , execute functions in order:
- begin()
- each function attribute
someattribute
- end()
i have this:
static void main(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)) { // found member `someattribute` attribute. // how can execute method? // i'd need c++ function pointer function. } } plugin.end(); } } }
thanks, paulh
once have methodinfo, can use invoke on that. if memberinfo returned getmembers points method, can cast methodinfo. can use code once have member info:
var method = mi methodinfo; if (method != null) method.invoke(plugin, null);
you can create delegate represents method. more suitable if need call more once.
action action = (action) delegate.createdelegate(typeof(action), plugin, method); // calls method pointed methodinfo action();
Comments
Post a Comment