2015-09-25 85 views
0

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

回答

0

簡短的回答是「沒有」。你不能說C#在特定的地方創建一個對象。 長的答案是「這取決於你的目的」。如果你只是想讓你的對象留在它創建的地方,可以考慮使用GCHandle.Alloc。您也可以搜索「固定對象」(SO question about pinned objects)。 您也可以固定一個對象數組並重用它的元素,就像它們在特定位置被「分配」一樣。