I'm writing a unity plugin to connect Native iOS functionality to Unity.
One of the things I have to do involves sending back strings from Objective-C(iOS) to C#(Unity) which is accomplished by writing a simple C extern function.
I found this post:
https://forum.unity3d.com/threads/plugins-sending-string-data.66435/
Which suggests using this helper function which can be returned through the C extern:
// Helper method to create C string copy
char* MakeStringCopy (const char* string)
{
if (string == NULL)
return NULL;
char* res = (char*)malloc(strlen(string) + 1);
strcpy(res, string);
return res;
}
I'm not very proficient with Unity so I don't know if this is causing a memory leak or not.
Looking at it from the pure Objective-C point of view, the function
The helper function is used within the C extern function like this:
return cStringCopy([objc_status UTF8String]);
So the memory used by the original string is managed automatically by Objective-C, however...
Once Unity receives the char pointer, will it deallocate the assigned memory automatically?
The C# unity script uses the function like this:
string someInfo = SDKWrapper_getInfo();
The answer from this question:
How to convert between a C# String and C Char pointer
Kind of relates to this (i think), so it really makes me think I have a memory leak here.
The accepted answer is wrong. Though some people mention that this way will lead to a memory leak that is not right. This way works fine in Unity and no leaks occurs (I tested it many times). Unity clearly states that
String values returned from a native method should be UTF–8 encoded and allocated on the heap. Mono marshalling calls free for strings like this.
Full answer
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With