progtips

任意のDLLを呼び出す(プラグインとして使う)

最終更新:

progtips

- view
メンバー限定 登録/ログイン

プラグイン側ソース

lib1.cs
namespace Classo
{
	public class Classa
	{
		public static string Description()
		{
			return "掛け算用ライブラリ";
		}

		public static long Run(long i, long j)
		{
			return (i * j);
		}
	}
}
lib2.cs
namespace Classo
{
	public class Classa
	{
		public static string Description()
		{
			return "足し算用ライブラリ";
		}

		public static long Run(long i, long j)
		{
			return (i + j);
		}
	}
}

使う側

using System;
using System.Reflection;
using System.IO;

class TestCode
{
	static void Go(string mod)
	{
		try {
			var assembly = Assembly.LoadFrom(mod);
			var module = assembly.GetModule(mod);
			var type = module.GetType("Classo.Classa");
			Object obj = Activator.CreateInstance(type);

			var Desc = type.GetMethod("Description");
			Console.WriteLine("  Desc:{0}", Desc.Invoke(null, null));

			var Run = type.GetMethod("Run");
			object[] param = { 100, 50 };
			object result = Run.Invoke(null, param);
			Console.WriteLine("  Call(100,50):{0}", result);
		}
		catch (Exception e)
		{
			Console.WriteLine("  エラー:{0}", e.Message);
		}
	}


	static void Main(string[] args)
	{
		string cwd = Directory.GetCurrentDirectory();
		foreach (var f in Directory.GetFiles(cwd, "*.dll"))
		{
			string n = f.Substring(cwd.Length+1);
			Console.WriteLine("DLLを発見しました:{0}", n);
			Go(n);
		}
	}
}
記事メニュー
目安箱バナー