I am currently working on a Unity project that runs on Windows and Android. I am basically using the Unity WebCamTexture class to access a connected camera and then send the image to my C++ code (dll on Windows, so on Android) which works with opencv for further processing.
While everything works fine on Windows, the exact same code is causing memory leaks on Android (RAM usage is constantly increasing on each frame). I have looked for several possible solutions on how to share the image with my C++ code. Each solution works fine on Windows and causes memory leaks on Android (the image processing works on Android too, just the leak is an issue)
Here is one working code example:
C#
Color32[] color = webcamTexture.GetPixels32();
byte[] data = Color32ArrayToByteArray(color);
IntPtr unmanagedArray = Marshal.AllocHGlobal(data.Length);
Marshal.Copy(data, 0, unmanagedArray, data.Length);
PrepareImage(unmanagedArray, camW, camH);
Marshal.FreeHGlobal(unmanagedArray);
C++
void PrepareImage(unsigned char* data,int w, int h){
cv::Mat textureC4(h, w, CV_8UC4, data);
cv::Mat textureC3;
cv::cvtColor(textureC4,textureC3,cv::COLOR_RGBA2RGB);
}
The memory leak starts as soon as I am trying to make any changes to the "texture" variable in the C++ part (such as changing from 4 channels to 3).
Since I am not experienced in C++, I am not surprised to run in such issues, but what confuses me the most is that it runs perfectly fine on windows. I'll be happy for any suggestions pointing me into a new direction. Thank you!
Update:
A few more details to the environments:
Unity Version: 2018.2.8f1
Tested NDK versions: 13b and 16b
Tested Phones: 1x Samsung S9, 2x Note 8
These additional solutions have also been tested and give the same results:
Furthermore I have also tried to create the pointer on the C++, let C# use that pointer and let finally C++ clean up the memory. This is causing still the same leaks. At this point I am wondering if it is a setup up problem so I am gonna create new projects and update about the results later
...I have now created a new Unity project that only runs the above code + the webcamtexture. Still the exact same behavior. At this point I suspect its the Android Studio project for my C++ code.
...I have now created a Visual Studio project to create the .so file. The memory is still leaking, even with an almost blank project.