Skip to content

Instantly share code, notes, and snippets.

@NN---
Last active July 26, 2017 21:30
Show Gist options
  • Save NN---/ea8b6fc5f2a5374300b61e458ee6f93e to your computer and use it in GitHub Desktop.
Save NN---/ea8b6fc5f2a5374300b61e458ee6f93e to your computer and use it in GitHub Desktop.
PInvoke SafeHandle via interface
using System;
using System.Runtime.InteropServices;
using FILETIME=System.Runtime.InteropServices.ComTypes.FILETIME;
namespace ConsoleApp4
{
interface ISafeProcessHandle
{
}
class SafeProcessHandle : SafeHandle, ISafeProcessHandle
{
public SafeProcessHandle(IntPtr invalidHandleValue, bool ownsHandle) : base(invalidHandleValue, ownsHandle)
{
}
protected override bool ReleaseHandle()
{
return true;
}
public override bool IsInvalid => false;
}
class CustomSafeHandleMarshaler : ICustomMarshaler
{
public static ICustomMarshaler GetInstance(string type)
{
return new CustomSafeHandleMarshaler();
}
public object MarshalNativeToManaged(IntPtr pNativeData)
{
return new SafeProcessHandle(pNativeData,true);
}
public IntPtr MarshalManagedToNative(object ManagedObj)
{
return ((SafeProcessHandle)ManagedObj).DangerousGetHandle();
}
public void CleanUpNativeData(IntPtr pNativeData)
{
}
public void CleanUpManagedData(object ManagedObj)
{
}
public int GetNativeDataSize()
{
return IntPtr.Size;
}
}
class Program
{
[DllImport("kernel32.dll", SetLastError = true, EntryPoint = "GetProcessTimes")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool GetProcessTimesViaInterface(
[MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(CustomSafeHandleMarshaler))]
ISafeProcessHandle hProcess,
out FILETIME lpCreationTime,
out FILETIME lpExitTime,
out FILETIME lpKernelTime,
out FILETIME lpUserTime);
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool GetProcessTimes(
SafeHandle hProcess,
out FILETIME lpCreationTime,
out FILETIME lpExitTime,
out FILETIME lpKernelTime,
out FILETIME lpUserTime);
static void Main(string[] args)
{
var p = new SafeProcessHandle(new IntPtr(-1), true);
GetProcessTimesViaInterface(p, out var c, out var e, out var k, out var u);
Console.WriteLine(u.dwLowDateTime);
GetProcessTimes(p, out c, out e, out k, out u);
Console.WriteLine(u.dwLowDateTime);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment