0
是否有任何方式強制class
或struct
在C#指向的存儲器中的特定塊,如在一個或MemoryStream
的byte
秒的數組?如果是這樣,是否還有一種方法可以在投射後調用其構造函數?我意識到實用性在這裏,它可能是不安全;我只是想了解該語言的各個方面。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; }
};
// ..
// 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;
}