How can I create a data structure starting at a specified memory address (without using new)?
I asked a similar question before, but I 开发者_开发问答only realized now that the answer I received isn't totally what I wanted.
If I simply have a pointer of some structure type, how can I either move to, or create an instance of the same structure type starting at an address specified by the struct pointer (which I have assigned an address to) without using "new".
That's what placement new
is for:
foo* p = new(0x9000) foo(bar);
If you are considering only C, where there is no constructors, once you have a pointer to a block of memory that is at least as big as the struct, then just casting that pointer to the appropriate type is sufficient.
If you are talking about C++, then it depends on the actual type. Whether it is spelled as struct
or class
does not make a real difference here. If the type has a trivial constructor then you can use the same approach than in C, as the constructor will effectively do nothing at all. If the object has a non-trivial constructor, then you need to call the constructor, and that has to be done with placement new.
I can think of two solutions
Use placement new instead of new.
For a C style structure simply copy the structure to the memory address and typecast it - bitwise copy
i.e.
CreateStructAtAddr(void* pOutput, mystruct* pInput) { *(mystruct*)pOutput = *pInput; }
I am ignoring check for valid memory for brevity
Okay. Let's say you have a structure of Type A.
A a;
A b;
If you want to copy b to a (i.e. to the address of a), you would use memcpy.
http://www.cplusplus.com/reference/clibrary/cstring/memcpy/.
This would make the content of "b" start at the adress of a, given by &a
.
If you have tow different structure types, ensure that both have the same size or you have unexpected behaviour.
精彩评论