Skip to content

Instantly share code, notes, and snippets.

@fearthecowboy
Created January 5, 2016 18:00
Show Gist options
  • Save fearthecowboy/07743c5937227318a3c3 to your computer and use it in GitHub Desktop.
Save fearthecowboy/07743c5937227318a3c3 to your computer and use it in GitHub Desktop.
Multi-platform DLLImport
using System;
using System.Runtime.InteropServices;
namespace MySample
{
internal class NativeMethods
{
// declare a delegate that fits
public delegate int MessageBoxFn(IntPtr hWnd, string text, string caption, int options);
// storage for the delegate
private static MessageBoxFn _messageBox;
// property to choose the platform-appropriate delegate at runtime (single-time initialization)
internal static MessageBoxFn MessageBox => _messageBox ?? (_messageBox = Environment.OSVersion.Platform == PlatformID.Win32NT ? (MessageBoxFn) MessageBoxWindows: MessageBoxLinux);
// a more complex example of choosing (still single-time init)
internal static MessageBoxFn MessageBox2
{
get
{
if (_messageBox != null)
{
return _messageBox;
}
// choose the per-platform implementation
switch (Environment.OSVersion.Platform)
{
case PlatformID.MacOSX:
return _messageBox = MessageBoxLinux;
case PlatformID.Unix:
return _messageBox = MessageBoxLinux;
case PlatformID.Win32NT:
return _messageBox = MessageBoxWindows;
// not available on this platform
default:
return _messageBox = (hWnd, text, caption, options) =>
{
// fall back to complaining.
Console.WriteLine("MessageBox Missing for this platform");
return -1;
};
}
}
}
// delcare the imported function that binds to the Windows version
[DllImport("user32.dll", CharSet = CharSet.Auto, EntryPoint = "MessageBoxW")]
private static extern int MessageBoxWindows(IntPtr hWnd, string text, string caption, int options);
// delcare the imported function that binds to the Linux version
[DllImport("user32.so", CharSet = CharSet.Auto, EntryPoint = "MyMessageBoxW")]
private static extern int MessageBoxLinux(IntPtr hWnd, string text, string caption, int options);
}
public class Program
{
private static void Main(string[] args)
{
// test the fuction
NativeMethods.MessageBox(IntPtr.Zero, "Helllo", "World", 0);
// or the more complicated selection
NativeMethods.MessageBox2(IntPtr.Zero, "Helllo", "World", 0);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment