- Home /
UnitySendMessage and NSString allocation
What would be right way of sending a custom NSString from objective-c to Unity?
I can do this, and the message is successfully received:
NSString * aString = [[NSString alloc] initWithString: @"a string"];
UnitySendMessage("MyObject", "Method", [aString UTF8String]);
But I am wondering how the memory allocation works across the message passing, I guess I have to do allocation (most examples do), but is the UnitySendMessage synchronous. I just want to make sure I have neither a memory leak, nor a dangling pointer problem.
Answer by $$anonymous$$ · Dec 27, 2012 at 11:54 AM
Hey there Dashesy :)
I've been interested in knowing the details of this myself as I've also been using UnitySendMessage extensively in plugin development.
First of all, from the original documentation it is stated that UnitySendMessage is not synchronous, that is, the call will actually probably be received the next frame: Official documentation
From what I was able to gather from around the web when it comes to unmanaged->managed calls between Objective-C and Mono using UnitySendMessage, it will copy any data which you send using UnitySendMessage. The source of this information comes from this thread: Original Source
I've been working accordingly to this for a while now, that is, right after I send any allocated memory from Objective-C to Mono, I deallocate it right away just as you would with any other alloc/release pair in traditional Objective-C code to avoid memory leaks. Actually I've mostly simplified the problem by just making use of autorelease objects, and it have never imposed any problems. You should be safe doing this :)
Hope this helps!
Thanks, yes that was most helpful and it makes perfect sense. I am going to rely on the auto pool, and let the variable go out of scope after UnitySend$$anonymous$$essage for memory to be reclaimed.