【发布时间】:2015-12-23 20:46:12
【问题描述】:
有没有办法强制 C# 中的 class 或 struct 指向特定的内存块,例如在 MemoryStream 或 bytes 的数组中?如果是这样,还有没有办法在转换后调用它的构造函数?我意识到这几乎没有实用性,而且可能不安全;我只是想了解语言的各个方面。
这是我所描述的一些演示 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;
}
【问题讨论】:
标签: c# c++ class memory casting