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
- takes a char pointer
- allocates some memory space based on the length of the original string
- copies the original string into this newly allocated space
- returns the new copied pointer
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.