// staticに押し込んだ版 //public static GetTrueDelegate GetTrue { get; } = // (GetTrueDelegate)new PInvokeProcInfo() // { // ProcName = "Bool_GetTrue", // EntryPoint = "Bool_GetTrue", // ModuleFile = DllFileName, // ReturnType = typeof(bool), // ParameterTypes = Array.Empty<Type>(), // CallingConvention = CallingConvention.StdCall, // CharSet = CharSet.Unicode // } // .CreateMethodInfo() // .CreateDelegate(typeof(GetTrueDelegate)); public bool GetTrue() { var procInfo = new PInvokeProcInfo() { ProcName = "Bool_GetTrue", EntryPoint = "Bool_GetTrue", ModuleFile = DllFileName, ReturnType = typeof(bool), ParameterTypes = Array.Empty <Type>(), CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Unicode }; var methodInfo = procInfo.CreateMethodInfo(); var getTrueDelegate = (GetTrueDelegate)methodInfo.CreateDelegate(typeof(GetTrueDelegate)); try { return(getTrueDelegate()); } catch (DllNotFoundException) { // DLLが存在しなければ実行時例外になる。 // DllImport(P/Invoke)でも同様に実行時例外になると思っており、Qiita記事と合わない…なぜ? throw; } }
static void Main(string[] args) { Console.WriteLine("Start"); // 自作DLLの実行 var ret = new BoolDelegate().GetTrue(); var invInfo = new PInvokeProcInfo() { ProcName = "MessageBox", EntryPoint = "MessageBoxW", ModuleFile = "User32.dll", ReturnType = typeof(Int32), ParameterTypes = new Type[] { typeof(IntPtr), typeof(string), typeof(string), typeof(Int32) }, CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Unicode }; // Invokeで実行 MethodInfo method = invInfo.CreateMethodInfo(); method.Invoke(null, new object[] { IntPtr.Zero, "Run Invoke", "test1", 0 }); // Delegateで実行 var messageBox = (MessageBoxDelegate)method.CreateDelegate(typeof(MessageBoxDelegate)); messageBox(IntPtr.Zero, $"ret = {ret}", "Window title", 0); }