概要
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);
}
}
}
}
以上。