类指针覆盖
本文关键字:覆盖 指针 | 更新日期: 2023-09-27 18:14:47
是否有任何方法可以强制c#中的class
或struct
指向特定的内存块,如MemoryStream
或byte
s数组?如果是这样,是否还有一种方法可以在强制转换后调用其构造函数?我意识到这几乎没有实用性,而且可能不安全;我只是想了解语言的各个方面。
下面是我所描述的一些演示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#在特定的地方创建对象。长一点的回答是"这取决于你的目的"。如果你只是想让你的对象停留在它创建的地方,考虑使用GCHandle.Alloc
。您还可以搜索"固定对象"(关于固定对象的问题)。你也可以固定一个数组的对象和重用它的元素,就像他们被"分配"在一个特定的地方。