//---------------------------------------------------------------------------- // Copyright (C) 2013-2015 Fabrice HARROUET (ENIB) // // Permission to use, copy, modify, distribute and sell this software // and its documentation for any purpose is hereby granted without fee, // provided that the above copyright notice appear in all copies and // that both that copyright notice and this permission notice appear // in supporting documentation. // The author makes no representations about the suitability of this // software for any purpose. // It is provided "as is" without express or implied warranty. //---------------------------------------------------------------------------- using System; using System.Text; using System.Runtime.InteropServices; using System.Diagnostics; public class Test { /*** "msvcrt" is used in DllImport This is the standard C library for Windows .NET loads "msvcrt.dll" Mono maps it to "libc.so.6" or "libc.dylib" (through /etc/mono/config) ***/ const string stdLibName="msvcrt"; [DllImport(stdLibName)] public static extern int getpid(); [DllImport(stdLibName)] private static extern IntPtr strncpy(StringBuilder dest, string src, int n); [DllImport(stdLibName)] private static extern IntPtr strerror(int errnum); public struct MyStruct { [MarshalAs(UnmanagedType.U1)] public bool b; public byte c; public short s; public int i; public long l; public float f; public double d; [MarshalAs(UnmanagedType.ByValTStr, SizeConst=16)] public string t; } /*** "myNativeLib" is used in DllImport .NET loads "myNativeLib.dll" (near to the assembly) Mono loads "libmyNativeLib.so" or "libmyNativeLib.dylib" ***/ [DllImport("myNativeLib",EntryPoint="myNativeFunction")] private static extern void myFunction(ref MyStruct ms); public static void Main(string[] args) { Console.WriteLine("testing getpid()"); try { int pid=getpid(); Console.WriteLine("--> {0}",pid); } catch(Exception e) { Console.WriteLine("!!! Exception: {0}",e); } Console.WriteLine("testing strncpy()"); try { StringBuilder sb=new StringBuilder(256); strncpy(sb,"copy this message",sb.Capacity); Console.WriteLine("--> {0}",sb.ToString()); } catch(Exception e) { Console.WriteLine("!!! Exception: {0}",e); } Console.WriteLine("testing strerror()"); try { IntPtr p=strerror(4); // 4: EINTR string s=Marshal.PtrToStringAnsi(p); Console.WriteLine("--> {0}",s); } catch(Exception e) { Console.WriteLine("!!! Exception: {0}",e); } Console.WriteLine("testing myFunction()"); MyStruct ms; ms.b=false; ms.c=1; ms.s=2; ms.i=3; ms.l=4; ms.f=5.5f; ms.d=6.6; ms.t="input"; try { myFunction(ref ms); Console.WriteLine("--> {0}, {1}, {2}, {3}, {4}, {5}, {6}, {7}", ms.b,ms.c,ms.s,ms.i,ms.l,ms.f,ms.d,ms.t); } catch(Exception e) { Console.WriteLine("!!! Exception: {0}",e); } } } //----------------------------------------------------------------------------