0

Is there any way to force a class or struct in C# to point to a specific block of memory, as in a MemoryStream or an array of bytes? If so, is there also a way to call its constructor after casting? I realize that there is little practicality in this, and it's potentially unsafe; I'm just trying to understand the facets of the language.

Here is some demo C++ code of what I'm describing:

#include <stdio.h>
#include <conio.h>

// Don't worry about the class definition... as the name implies, it's junk
class JunkClass
{
private:
    int a;
    int b;

public:
    JunkClass(int aVal, int bVal) : a(aVal), b(bVal) { }
    ~JunkClass() { }

    static void *operator new(size_t size, void *placement){ return placement; }
};

//..

// Assuming 32-bit integer and no padding
// This will be the memory where the class pointer is cast from
unsigned char pBytes[] = { 0, 0, 0, 0, 0, 0, 0, 0 };

//..

int main(void)
{
    // The next two lines are what I want to do in C#
    JunkClass *pClass = (JunkClass *)pBytes; // Class pointer pointing to pBytes
    pClass = new(pBytes) JunkClass(0x44332211, 0x88776655); // Call its constructor using placement new operator

    // Verify bytes were set appropriately by the class
    // This should print 11 22 33 44 55 66 77 88 to the console
    unsigned char *p = pBytes;
    for (int i = 0; i < 8; i++)
        printf("%02X ", *(p++));

    // Call destructor
    pClass->~JunkClass();
    while (!_kbhit());
    return 0;
}

1 Answers1

0

The short answer is "no". You cannot say C# to create an object in a specific place. The long answer is "it depends on your purpose". If you just want your object to stay where it was created consider using GCHandle.Alloc. You can also search for "pinned objects"(SO question about pinned objects). Also you can pin an array of objects and reuse it's elements like they are "allocated" in a specific place.

Community
  • 1
  • 1