C#:类指针重写

C#:类指针重写,c#,c++,class,memory,casting,C#,C++,Class,Memory,Casting,有没有办法强制C中的类或结构指向特定的内存块,如内存流或字节数组?如果是这样,是否还有一种方法可以在强制转换后调用其构造函数?我意识到这里面没有什么实用性,而且有潜在的不安全性;我只是想了解语言的各个方面 这里是一些我所描述的演示C++代码: #include <stdio.h> #include <conio.h> // Don't worry about the class definition... as the name implies, it's junk c

有没有办法强制C中的
结构
指向特定的内存块,如
内存流
字节
数组?如果是这样,是否还有一种方法可以在强制转换后调用其构造函数?我意识到这里面没有什么实用性,而且有潜在的不安全性;我只是想了解语言的各个方面

这里是一些我所描述的演示C++代码:

#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; }
};
//

int main(无效)
{
//接下来的两行是我在C中要做的#
JunkClass*pClass=(JunkClass*)pBytes;//指向pBytes的类指针
pClass=new(pBytes)JunkClass(0x44332211,0x88776655);//使用placement new运算符调用其构造函数
//验证类是否正确设置了字节
//这将在控制台上打印11 22 33 44 55 66 77 88
无符号字符*p=PB字节;
对于(int i=0;i<8;i++)
printf(“%02X”,*(p++);
//调用析构函数
pClass->~JunkClass();
而(!_kbhit());
返回0;
}
简短的回答是“不”。你不能说C#来在一个特定的地方创建一个对象。 答案很长,“这取决于你的目的”。如果你只想让你的对象停留在它创建的地方,考虑使用<代码> GCHANDLE。您还可以搜索“固定对象”()。 您还可以固定一个对象数组并重用其元素,就像它们被“分配”到特定位置一样

// 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;
}