【问题标题】:C# : Class pointer overrideC#:类指针覆盖
【发布时间】:2015-12-23 20:46:12
【问题描述】:

有没有办法强制 C# 中的 classstruct 指向特定的内存块,例如在 MemoryStreambytes 的数组中?如果是这样,还有没有办法在转换后调用它的构造函数?我意识到这几乎没有实用性,而且可能不安全;我只是想了解语言的各个方面。

这是我所描述的一些演示 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


    【解决方案1】:

    简短的回答是“不”。您不能说 C# 在特定位置创建对象。 长答案是“这取决于你的目的”。如果您只想让您的对象留在创建它的位置,请考虑使用GCHandle.Alloc。您还可以搜索“固定对象”(SO question about pinned objects)。 您还可以固定一组对象并重用它的元素,就像它们在特定位置“分配”一样。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-12
      • 1970-01-01
      • 1970-01-01
      • 2020-03-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-16
      相关资源
      最近更新 更多