Notifications
Clear all

[Closed] Initializing a WStr from a MCHAR*

Sorry if this is common knowledge but I couldn’t find any definitive answer in the SDK documentation nor in the various samples and open source projects I looked at.

Consider the following code:

MCHAR* buf;
MSTR s;
...
s = buf;

Is ownership of the memory pointed by buf transfered to the MSTR, or is the string copied into the MSTR? In other words, do I need to deallocate buf after I initialized the MSTR from it? If so, how?

4 Replies

it is copied into the WStr object until a null character is reached. as for ownership it really depends on how buf was created. if …

MCHAR* buf = new MCHAR[10];

then yes with

delete [] buf;

if with…

MCHAR* buf = node->GetName();

then no
or if

MCHAR temp[100];
 MCHAR* buf = temp;

then no

Thanks for the answer.

Actually, and I should probably have mentioned this from the beginning, the MCHAR* was allocated by Max itself in ILoad::ReadWStringChunk():

MCHAR* buf;
const IOResult result = iload->ReadWStringChunk(&buf);
MSTR* s = ...; // valid pointer to a MSTR
if (result == IO_OK)
    *s = buf;

So I expect that I cannot simply delete[] buf, I probably need to call a Max function to deallocate the string on Max’ side.

It’s probably cleaned up in the CloseChunk() call so you don’t need to release any memory in all the examples it copied somewhere immediately after its read.

btw the “prefered” method would be to use the constructor not the assignment operator

MSTR mystr(buf);

or

MSTR* str = NULL;
if(iload->ReadWStringChunk(&buf) == IO_OK)
	str = new MSTR(buf);

Thanks!

The reason I’m using the assignment operator is because I’m being passed a pointer to an existing MSTR object:

https://github.com/appleseedhq/appleseed-max/blob/2e5a0d1d16329140e3063c4383cb8a07a39b9978/src/appleseed-renderer/utilities.h#L177-L186