This is sample code that throws a MarshalDirectiveException. A good explanation of SafeHandle can be found here ,
[SuppressUnmanagedCodeSecurity]
private delegate SafeHandle testDelegate();
[SuppressUnmanagedCodeSecurity]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
public static SafeHandle test(){
FileStream fs=new FileStream("a.txt", FileMode.Create);
return fs.SafeFileHandle;
}
private static void Main(){
MethodInfo methodInfo = typeof (Program).GetMethod("test", BindingFlags.Static | BindingFlags.Public);
Delegate delegateInstance = Delegate.CreateDelegate(typeof (testDelegate), methodInfo);
IntPtr fcePtr = Marshal.GetFunctionPointerForDelegate(delegateInstance);
}
, , int IntPtr, , Dipose patter. , , , g, . , . . , . SafeHandle.
[DllImport("mydll")]
public static extern void naked(IntPtr nakedHandle);
private static void Main(){
IntPtr intPtr = getHandle();
naked(intPtr);
}
private static IntPtr getHandle(){
FileStream fs = new FileStream("myfile", FileMode.CreateNew);
IntPtr ha = fs.Handle;
return ha;
}