O'Reilly logo

C# Cookbook by Jay Hilyard, Stephen Teilhet

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

16.8. Switching Unknown Pointer Types

Problem

You need a generic method that accepts two pointers and switches the addresses that each pointer points to. In other words, if X points to an integer variable Foo and Y points to an integer variable Bar, you want to switch X so that it points to Bar and switch Y so that it points to Foo.

Solution

Create a method that accepts two void pointers. The following method accepts two pointers to void by reference. The by reference is required since we are actually switching the values contained in the pointer variables, not the value that the pointer is pointing to:

public unsafe void Switch(ref void* x, ref void* y)
{
    void* temp = x;
    x = y;
    y = temp;
}

The following test code calls the Switch method with two integer variables that point to different memory locations:

public unsafe void TestSwitch( )
{
    int x = 100;
    int y = 20;
    int* ptrx = &x;
    int* ptry = &y;

    Console.WriteLine(*ptrx + "\t" + (int)ptrx);
    Console.WriteLine(*ptry + "\t" + (int)ptry);

    // Convert int* to void*
    void* voidx = (void*)ptrx;
    void* voidy = (void*)ptry;

    // Switch pointer values
    Switch(ref voidx, ref voidy);

    // Convert returned void* to a usable int*
    ptrx = (int*)voidx;
    ptry = (int*)voidy;

    Console.WriteLine(*ptrx + "\t" + (int)ptrx);
    Console.WriteLine(*ptry + "\t" + (int)ptry);
}

The following is displayed:

100     1243108
20      1243104
20      1243104
100     1243108

The TestSwitch method could just have easily been written with another data type, such as a byte, shown here:

public unsafe void ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required