PlugIn function implementation with C#

2019-08-25 00:19发布

问题:

I need to call a function to call user's dll in C#.

For example, when user makes a abc.dll with class ABC, I want to load the dll to run the methods xyz(a) in the class.

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

How can I implement those functions in C#?

ADDED

This is plugin code, and the dll is copied as plugin/plugin.dll.

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

This is the one that calls this plugin.

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);
    }
}

回答1:

It can be translated in C# and .NET to the following:

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

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

It is called 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 for more details