0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

cscの作法 その280

0
Last updated at Posted at 2022-09-23

概要

cscの作法、調べてみた。
練習問題やってみた。

練習問題

Marshal.GetDelegateForFunctionPointerを使ってください。

方針

  • dllimport使わない、dllインポート。

参考にしたページ

サンプルコード

using System;
using System.Runtime.InteropServices;

namespace App
{
	public class LateBinding : IDisposable {
		[DllImport("kernel32", CharSet = CharSet.Unicode, SetLastError = true)]
		private static extern IntPtr LoadLibrary([MarshalAs(UnmanagedType.LPWStr)] string lpFileName);
		[DllImport("kernel32", SetLastError = true)]
		private static extern bool FreeLibrary(IntPtr hModule);
		[DllImport("kernel32", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = false)]
		private static extern IntPtr GetProcAddress(IntPtr hModule, [MarshalAs(UnmanagedType.LPStr)] string lpProcName);
		private IntPtr _module;
		public LateBinding(string filename) {
			_module = LateBinding.LoadLibrary(filename);
			if (_module != IntPtr.Zero) 
			{
				return;
			}
			int result = Marshal.GetHRForLastWin32Error();
			throw Marshal.GetExceptionForHR(result);
		}
		public Delegate GetDelegate(string procName, Type delegateType) {
			IntPtr ptr = LateBinding.GetProcAddress(_module, procName);
			if (ptr != IntPtr.Zero) 
			{
				Delegate d = Marshal.GetDelegateForFunctionPointer(ptr, delegateType);
				return d;
			}
			int result = Marshal.GetHRForLastWin32Error();
			throw Marshal.GetExceptionForHR(result);
		}
		public void Dispose() {
			if (_module != IntPtr.Zero) 
			{
				LateBinding.FreeLibrary(_module);
			}
		}
	}
	public delegate int MessageBox(IntPtr hwnd, [MarshalAs(UnmanagedType.LPWStr)] string text, [MarshalAs(UnmanagedType.LPWStr)] string Caption, int type);
	static class Program {
		[STAThread]
		static void Main() {
			using (LateBinding b = new LateBinding("user32.dll")) 
			{
				MessageBox m = (MessageBox) b.GetDelegate("MessageBoxW", typeof(MessageBox));
				m(IntPtr.Zero, "hello c#", "App", 0);
			}
		}
	}
}





以上。

0
0
0

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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?