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

  1. takes char pointer
  2. allocates memory space based on length of original string
  3. copies original string newly allocated space
  4. 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

Popular posts from this blog

python - Operations inside variables -

Generic Map Parameter java -

arrays - What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it? -