Using C types with garbage collection

G

Gary Nastrasio

Is it possible to use "normal" C types with garbage collection? Here's
the function I'd like to write, but not have to worry about deallocation:


char* ConvertStringToChar(String* pString)
{
const wchar_t __pin *pStrChars;

char* pOutString = (char*)malloc(sizeof(char) * 256);

pStrChars = PtrToStringChars(pInString);
wcstombs(pOutString, pStrChars, (pInString->Length + 1) * 2);

return pOutString;
}

And then use it such as:

MessageBoxA(NULL, ConvertStringToChar(new String("Hello")), "Test", MB_OK);


Thanks,

Gary
 
W

William DePalo [MVP VC++]

Gary Nastrasio said:
Is it possible to use "normal" C types with garbage collection? Here's
the function I'd like to write, but not have to worry about deallocation:


char* ConvertStringToChar(String* pString)
{
const wchar_t __pin *pStrChars;

char* pOutString = (char*)malloc(sizeof(char) * 256);

pStrChars = PtrToStringChars(pInString);
wcstombs(pOutString, pStrChars, (pInString->Length + 1) * 2);

return pOutString;
}

And then use it such as:

MessageBoxA(NULL, ConvertStringToChar(new String("Hello")), "Test",
MB_OK);

I'm not sure I understand what you are asking. But, if you are asking if you
can allocate memory with malloc() and have the garbage collector deallocate
it, then the answer is no.

BTW, while we are on the subject of C-isms, do you know about the _alloca()
function. It makes allocations from the stack. These allocations evaporate
into the ether upon leaving the function in which the call was made without
any effort on your part. So, you couldn't use it in your conversion
function, but you could use it immediately before the call to MessageBoxA().

Regards,
Will
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top