ios - Objective-C to C to C# unity wrapper possibly causing memory leak? -
i'm writing unity plugin connect native ios functionality unity.
one of things have involves sending strings objective-c(ios) c#(unity) accomplished writing simple c extern function.
i found post:
https://forum.unity3d.com/threads/plugins-sending-string-data.66435/
which suggests using helper function can returned through c extern:
// helper method 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 proficient unity don't know if causing memory leak or not.
looking @ pure objective-c point of view, function
- takes char pointer
- allocates memory space based on length of original string
- copies original string newly allocated space
- returns new copied pointer
the helper function used within c extern function this:
return cstringcopy([objc_status utf8string]); so memory used original string managed automatically objective-c, however...
once unity receives char pointer, deallocate assigned memory automatically?
the c# unity script uses function this:
string someinfo = sdkwrapper_getinfo(); the answer question:
how convert between c# string , c char pointer
kind of relates (i think), makes me think have memory leak here.
yes, leak memory. solution pass managed chunk of memory (i.e. stringbuilder) native function, i.e.:
[dllimport(...)] private static extern int getinfo ([marshalas(unmanagedtype.lpwstr)]stringbuilder dst, int dstcapacity); private void somemethod() { var sb = new stringbuilder(8192); // perhaps function can indicate whether capacity large enough var success = getinfo(sb, sb.capacity); } you can see similar example on this page.
Comments
Post a Comment