[Mono-dev] (no subject)

Jonathan Pryor jonpryor at vt.edu
Sat Sep 10 10:39:03 EDT 2005


On Thu, 2005-09-08 at 16:03 +0530, Sridhar Kulkarni wrote:
> Hi,
> 
> I am having GetPathName method call in my C# code. I am using the same 
> source file to compile both on windows and linux. This method calls some 
> WIN32 APIs within it. This function also has linux specific code. As there 
> is no #ifdef directive is not available in C# how to go about this. I tried 
> using
> 
> #if __linux
> 
> ...............
> .....
> 
> #else //for windows
> ..........
> .  .. .
> #endif
> 
> But this doesn't work. How to go about this.

This will work, but __MonoCS__ is the only pre-set #define symbol, and
this only indicates that `mcs' is being used to compile the code, *not*
what platform you're running on (as it could be mcs on Win32 as easily
as mcs on Linux).

Consequently, for this approach to work you need to add a
-define:__linux argument to mcs to compile your Linux-specific code, e.g

	$ mcs -define:__linux my-program.cs

However, using #if is typically undesirable.  It is generally preferable
to do a runtime platform check and change behavior at runtime, e.g.:

	class Foo {
		[DllImport ("win32-lib")]
		private static extern void Win32Call ();

		[DllImport ("linux-lib")]
		private static extern void LinuxCall ();

		public static void Call ()
		{
			if (System.IO.Path.DirectorySeparatorChar == '\\') {
				Win32Call ();
			}
			else {
				LinuxCall ();
			}
		}
	}

If the unmanaged library export has the same name, it is preferable to
use the Win32 library name and provide a dllmap for Mono:

	class Foo {
		[DllImport ("win32-lib")]
		private static extern void NativeCall ();

		public static void Call ()
		{
			NativeCall ();
		}
	}

And then provide a ASSEMBLY-NAME.dll.config file with the contents:

	<configuration>
		<dllmap dll="win32-lib" target="linux-lib"/>
	</configuration>

See also: 

	http://www.mono-project.com/DllMap
	http://www.mono-project.com/Interop_with_Native_Libraries
	http://www.mono-project.com/FAQ:_Technical#How_to_detect_the_execution_platform_.3F

 - Jon





More information about the Mono-devel-list mailing list