LoginSignup
10
14

More than 5 years have passed since last update.

.Net用DLLを動的に呼び出す

Last updated at Posted at 2012-12-26

概要

C++のDLLを動的に呼び出すにはDllImportを使用しますが、.Net用DLLはDllImportでは呼び出せません。.Net用DLLを呼び出すにはSystem.Reflectionの機能を使用します。

プログラム例

呼び出し先のクラスライブラリ(ClassLibrary1.dll)

namespace namespace1
{
   public class Class1
   {
        public string method(string a,string b)
        {
            return a + ":" + b; 
        }
   }
}

呼び出し元プログラム

using System.Reflection
…(略)…
Assembly asm = Assembly.LoadFrom("ClassLibrary1.dll");
Module mod = asm.GetModule("ClassLibrary1.dll");
System.Type type = mod.GetType("namespace1.Class1");
if(type != null) {
    Object obj = Activator.CreateInstance(type);

    Type[] types = new Type[2];
    types[0] = typeof(string);
    types[1] = typeof(string);
    MethodInfo method = type.GetMethod("method", types);
    object ret = method.Invoke(obj, new string[] { "abc", "def" });

    Console.WriteLine(ret);
}

dynamicを使用した例

dynamicを使用すると、自然な記法でメソッド呼び出しが記述できます。

using System.Reflection
…(略)…
Assembly asm = Assembly.LoadFrom("ClassLibrary1.dll");
Module mod = asm.GetModule("ClassLibrary1.dll");
System.Type type = mod.GetType("namespace1.Class1");
if (type != null) {
    dynamic obj = Activator.CreateInstance(type);

    var ret = obj.method("abc", "def");

    Console.WriteLine(ret);
}
10
14
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
14