The last post wasn’t really platform independent. Not at runtime anyway. I discovered that the technique is to create a class that delivers the operating system.
public class OperatingSystem
{
[DllImport ("libc")]
static extern int uname (IntPtr buf);
public static string DetectOS ()
{
string style;
if( !IsUnix )
{
style = "Windows";
return style;
}
IntPtr buf = UnixMarshal.AllocHeap(8192);
if( uname (buf) != 0 )
{
style = "Unix";
return style;
}
style = UnixMarshal.PtrToStringUnix (buf);
UnixMarshal.FreeHeap(buf);
return style;
}
static bool IsUnix
{
get {
int p = (int) Environment.OSVersion.Platform;
return ((p == 4) || (p == 128));
}
}
}
Now all you have to do is use refelction. So substituting yesterday’s first technique for MacOS in the static Main method
if( OperatingSystem.DetectOS() == "Darwin" )
{
System.Reflection.Assembly assemblyMonoMac = System.Reflection.Assembly.Load("MonoMac");
Type nsapplication = assemblyMonoMac.GetType("MonoMac.AppKit.NSApplication");
nsapplication.GetMethod("Init").Invoke( null, new object[] {});
}
The following code fragment creates a sound buffer and then plays it. You could equally apply the same technique to yesterday’s example of turning an icon into a pixbuf.
object sndPlayer;
string OS = OperatingSystem.DetectOS();
if( OS == "Darwin" )
{
System.Reflection.Assembly assemblyMonoMac = System.Reflection.Assembly.Load("MonoMac");
Type nsdata = assemblyMonoMac.GetType("MonoMac.Foundation.NSData");
object sounddata = nsdata.GetMethod("FromStream").Invoke( null, new object[] { s });
sndPlayer = assemblyMonoMac.CreateInstance("MonoMac.AppKit.NSSound",false,System.Reflection.BindingFlags. CreateInstance,null,new object[] { sounddata }, null, null );
StartReminders();
}
else
{
sndPlayer = new SoundPlayer(s);
(sndPlayer as SoundPlayer).LoadCompleted += Handle_sndPlayer_LoadCompleted;
(sndPlayer as SoundPlayer).LoadAsync();
}
if( OS == "Darwin" )
{
System.Reflection.Assembly assemblyMonoMac = System.Reflection.Assembly.Load("MonoMac");
Type nssound = assemblyMonoMac.GetType("MonoMac.AppKit.NSSound");
System.Reflection.MethodInfo methodInfo = nssound.GetMethod("Play");
methodInfo.Invoke( sndPlayer, new object[] {});
}
else
(sndPlayer as SoundPlayer).Play();
What’s left to explore is displaying unicode strings, but that’s another topic.