is there way force class
or struct
in c# point specific block of memory, in memorystream
or array of byte
s? if so, there way call constructor after casting? realize there little practicality in this, , it's potentially unsafe; i'm trying understand facets of language.
here demo c++ code of i'm describing:
#include <stdio.h> #include <conio.h> // don't worry class definition... 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 , no padding // memory class pointer cast unsigned char pbytes[] = { 0, 0, 0, 0, 0, 0, 0, 0 };
//..
int main(void) { // next 2 lines want in c# junkclass *pclass = (junkclass *)pbytes; // class pointer pointing pbytes pclass = new(pbytes) junkclass(0x44332211, 0x88776655); // call constructor using placement new operator // verify bytes set appropriately class // should print 11 22 33 44 55 66 77 88 console unsigned char *p = pbytes; (int = 0; < 8; i++) printf("%02x ", *(p++)); // call destructor pclass->~junkclass(); while (!_kbhit()); return 0; }
the short answer "no". cannot c# create object in specific place. long answer "it depends on purpose". if want object stay created consider using gchandle.alloc
. can search "pinned objects"(so question pinned objects). can pin array of objects , reuse it's elements "allocated" in specific place.
Comments
Post a Comment