External Strings and the GC

BlitzMax Forums/BlitzMax Programming/External Strings and the GC

Gabriel(Posted 2009) [#1]
I'm just really wanting to check that my understanding of how the GC collects strings is good. I tried digging out the source, but couldn't find it.

I'm passing strings back and forth from/to C++, treating them as char arrays. I use the $z notation in the Extern declarations. If I get a string as a return type from C++, I'm wondering whether the GC will attempt to free the memory used by the char array. I think it won't. I think it copies the data from the char array to memory allocated to it and frees that instead. But I'd like to be sure because I need to know whether I should pass the string as I am and delete it in my C++ DLL when I'm done with it, or whether I need to copy the string to a second char array before sending it so that the copy the C++ DLL works with is not collected prematurely.

I suppose I should also confirm that how it is in reverse too. So when I send a string to C++ as a char* using $z in the declaration is that collected? Do I need to copy that to create a new char array in C++ and copy the contents from one to the other? Or can I just use that pointer, knowing that BlitzMax will never free it?


Azathoth(Posted 2009) [#2]
You need to free the strings you send from blitzmax to C++ you need to free yourself with MemFree


Difference(Posted 2009) [#3]
With $z BlitzMax takes care of freeing. You should call those with normal blitz string, not with a char array.

If you use String.ToCsting() , you have to free the memory associated with the pointer:
Extern
    Function aiIsExtensionSupported:Int(pFile$z)
End Extern

Local myBlitzString:string

aiIsExtensionSupported(myBlitzString)

or

Extern
    Function aiIsExtensionSupported:Int(pFile:Byte Ptr)
End Extern

Local myBlitzString:string

Local myPtr:Byte Ptr = String.ToCsting(myBlitzString)

aiIsExtensionSupported(myPtr)

MemFree myPtr


You can use the pointer to returned char arrays, Bmax will not free them.

Bmax will free the native Bmax strings it creates from String.FromCstring(pChar:Byte ptr)


Gabriel(Posted 2009) [#4]
EDITED:

Thanks Peter. You reminded me of the functions ToCString and FromCString and I used those as search terms, and they confirmed that you're right. The memory is freed automatically when you use $z. Thanks again.

I was concerned that I had a memory leak in a couple of my modules, and was going to fix it, but this tells me that there is no leak.