HandleRef Sample

This sample demonstrates how to prevent garbage collection on a managed object before the unmanaged function completes. It also demonstrates how to use function overloading to pass a null reference (Nothing in Visual Basic) instead of a reference to a value type.

The HandleRef sample uses the following unmanaged function, shown with its original function declaration:

  • ReadFile exported from Kernel32.dll.

    BOOL ReadFile(
       HANDLE hFile, 
       LPVOID lpBuffer, 
       DWORD nNumberOfBytesToRead, 
       LPDWORD lpNumberOfBytesRead, 
       LPOVERLAPPED lpOverlapped);
    

The original structure passed to the function contains the following elements:

typedef struct _OVERLAPPED { 
    ULONG_PTR  Internal; 
    ULONG_PTR  InternalHigh; 
    DWORD  Offset; 
    DWORD  OffsetHigh; 
    HANDLE hEvent; 
} OVERLAPPED; 

In this sample, the Overlapped structure and the Overlapped2 class contain IntPtr types instead of pointer types and the HANDLE type. The StructLayoutAttribute attribute is set to ensure that the members are arranged in memory sequentially, in the order in which they appear.

The LibWrap class contains managed prototypes for the ReadFile and ReadFile2 methods. ReadFile passes the Overlapped structure as one of the parameters. By overloading the ReadFile method, the sample can pass a null reference (Nothing in Visual Basic) instead of a reference to the structure, when needed. Neither C# nor Visual Basic 2005 permit passing a null reference (Nothing) directly.

ReadFile2 passes the Overlapped2 class. Classes, which are reference types, are passed as In parameters by default. Applying the InAttribute and OutAttribute attributes to the declaration causes Overlapped2 to be marshaled as an In/Out parameter. The sample can pass a null reference (Nothing) directly, when needed, instead of a class, because classes are reference types and you can pass a null reference (Nothing) in their place. The App class creates a HandleRef wrapper for the FileStream to prevent garbage collection from occurring before calls to ReadFile or ReadFile2 are complete.

Declaring Prototypes

' Declares a managed structure for the unmanaged structure.
<StructLayout(LayoutKind.Sequential)> _
Public Structure Overlapped
    ' ...
End Structure

' Declares a managed class for the unmanaged structure.
<StructLayout(LayoutKind.Sequential)> _
Public Class Overlapped2
    ' ...
End Class

Public Class LibWrap
    ' Declares a managed prototypes for unmanaged functions.
    ' Because Overlapped is a structure, you cannot pass Nothing as a
    ' parameter. Instead, declares an overloaded method.
    Overloads Declare Ansi Function ReadFile Lib "Kernel32.dll" ( _
        ByVal hndRef As HandleRef, _
        ByVal buffer As StringBuilder, _
        ByVal numberOfBytesToRead As Integer, _
        ByRef numberOfBytesRead As Integer, _
        ByRef flag As Overlapped) As Boolean

    ' Declares an int instead of a structure reference for 'flag'
    Overloads Declare Ansi Function ReadFile Lib "Kernel32.dll" ( _
        ByVal hndRef As HandleRef, _
        ByVal buffer As StringBuilder, _
        ByVal numberOfBytesToRead As Integer, _
        ByRef numberOfBytesRead As Integer, _
        ByVal flag As IntPtr) As Boolean

    ' Because Overlapped2 is a class, you can pass Nothing as a parameter.
    ' No overloading is needed.
    Declare Ansi Function ReadFile2 Lib "Kernel32.dll" Alias "ReadFile" ( _
        ByVal hndRef As HandleRef, _
        ByVal buffer As StringBuilder, _
        ByVal numberOfBytesToRead As Integer, _
        ByRef numberOfBytesRead As Integer, _
        <[In], Out> ByVal flag As Overlapped2) As Boolean
End Class
// Declares a managed structure for the unmanaged structure.
[StructLayout(LayoutKind.Sequential)]
public struct Overlapped
{
    // ...
}

// Declares a managed class for the unmanaged structure.
[StructLayout(LayoutKind.Sequential)]
public class Overlapped2
{
    // ...
}

public class LibWrap
{
   // Declares managed prototypes for unmanaged functions.
   // Because Overlapped is a structure, you cannot pass null as a
   // parameter. Instead, declares an overloaded method.
    [DllImport("Kernel32.dll")]
    public static extern bool ReadFile(
        HandleRef hndRef,
        StringBuilder buffer,
        int numberOfBytesToRead,
        out int numberOfBytesRead,
        ref Overlapped flag );

    [DllImport("Kernel32.dll")]
    public static extern bool ReadFile(
        HandleRef hndRef,
        StringBuilder buffer,
        int numberOfBytesToRead,
        out int numberOfBytesRead,
        IntPtr flag ); // Declares an int instead of a structure reference.

    // Because Overlapped2 is a class, you can pass null as parameter.
    // No overloading is needed.
    [DllImport("Kernel32.dll", EntryPoint="ReadFile")]
    public static extern bool ReadFile2(
        HandleRef hndRef,
        StringBuilder buffer,
        int numberOfBytesToRead,
        out int numberOfBytesRead,
        Overlapped2 flag);
}
// Declares a managed structure for the unmanaged structure.
[StructLayout(LayoutKind::Sequential)]
public value struct Overlapped
{
    // ...
};

// Declares a managed class for the unmanaged structure.
[StructLayout(LayoutKind::Sequential)]
public ref class Overlapped2
{
    // ...
};

public ref class LibWrap
{
public:
    // Declares managed prototypes for unmanaged functions.
    // Because Overlapped is a structure, you cannot pass null as a
    // parameter. Instead, declares an overloaded method.
    [DllImport("Kernel32.dll")]
    static bool ReadFile(
        HandleRef hndRef,
        StringBuilder^ buffer,
        int numberOfBytesToRead,
        int numberOfBytesRead,
        Overlapped% flag );

    [DllImport("Kernel32.dll")]
    static bool ReadFile(
        HandleRef hndRef,
        StringBuilder^ buffer,
        int numberOfBytesToRead,
        int% numberOfBytesRead,
        IntPtr flag ); // Declares an int instead of a structure reference.

    // Because Overlapped2 is a class, you can pass null as parameter.
    // No overloading is needed.
    [DllImport("Kernel32.dll", EntryPoint="ReadFile")]
    static bool ReadFile2(
        HandleRef hndRef,
        StringBuilder^ buffer,
        int numberOfBytesToRead,
        int% numberOfBytesRead,
        Overlapped2^ flag);
};

Calling Functions

Public Class App
    Public Shared Sub Main()
        Dim fs As New FileStream("HandleRef.txt", FileMode.Open)
        ' Wraps the FileStream handle in HandleRef to prevent it
        ' from being garbage collected before the call ends.
        Dim hr As New HandleRef(fs, fs.SafeFileHandle.DangerousGetHandle())
        Dim buffer As New StringBuilder(5)
        Dim read As Integer = 0
        ' Platform invoke holds the reference to HandleRef until the
        ' call ends.
        LibWrap.ReadFile(hr, buffer, 5, read, IntPtr.Zero)
        Console.WriteLine("Read {0} bytes with struct parameter: {1}", read, buffer)
        LibWrap.ReadFile2(hr, buffer, 5, read, Nothing)
        Console.WriteLine("Read {0} bytes with class parameter: {1}", read, buffer)
    End Sub
End Class
public class App
{
    public static void Main()
    {
        FileStream fs = new FileStream("HandleRef.txt", FileMode.Open);
        // Wraps the FileStream handle in HandleRef to prevent it
        // from being garbage collected before the call ends.
        HandleRef hr = new HandleRef(fs, fs.SafeFileHandle.DangerousGetHandle());
        StringBuilder buffer = new StringBuilder(5);
        int read = 0;
        // Platform invoke holds a reference to HandleRef until the call
        // ends.
        LibWrap.ReadFile(hr, buffer, 5, out read, IntPtr.Zero);
        Console.WriteLine("Read {0} bytes with struct parameter: {1}", read, buffer);
        LibWrap.ReadFile2(hr, buffer, 5, out read, null);
        Console.WriteLine("Read {0} bytes with class parameter: {1}", read, buffer);
    }
}
public ref class App
{
public:
    static void Main()
    {
        FileStream^ fs = gcnew FileStream("HandleRef.txt", FileMode::Open);
        // Wraps the FileStream handle in HandleRef to prevent it
        // from being garbage collected before the call ends.
        HandleRef hr = HandleRef(fs, fs->SafeFileHandle->DangerousGetHandle());
        StringBuilder^ buffer = gcnew StringBuilder(5);
        int read = 0;
        // Platform invoke holds a reference to HandleRef until the call
        // ends.
        LibWrap::ReadFile(hr, buffer, 5, read, IntPtr::Zero);
        Console::WriteLine("Read {0} bytes with struct parameter: {1}", read, buffer);
        LibWrap::ReadFile2(hr, buffer, 5, read, nullptr);
        Console::WriteLine("Read {0} bytes with class parameter: {1}", read, buffer);
    }
};

See Also

Concepts

Miscellaneous Marshaling Samples

Platform Invoke Data Types

Creating Prototypes in Managed Code