Will memory allocated in a c++ DLL be recognized by c# - Stack Overflow

I can't figure out a good way to word this question since I'm kind of new to c++, but I found

I can't figure out a good way to word this question since I'm kind of new to c++, but I found an image loading library called stb_image. It's pretty neat, but I have two questions I need to make sure of.

Firstly, I need to make sure that my .NET application won't garbage collect the memory allocated by the c++ library. The way I'm doing the interop right now is getting a C# IntPtr from an unsigned char* in c++ and calculating the length of the buffer by using the image width, height, bit depth, and channels per pixel. This works great in Unity, but I need to make sure the memory isn't ever freed until I want it to be because I will need to save a file with a copy of the image later. I also want to make sure the memory won't be overwritten by something Unity does.

Secondly, the stb_image library also has a free function which takes an unsigned char* as an argument, however I'm not sure if passing an IntPtr from C# will actually deallocate the memory, and I'm not sure how to check either.

Here is a snippet of how I am using this:

// C++ header
__declspec(dllexport) unsigned char* GetImage(const char* filename, int* width, int* height, int* comp);
// C# code
int width = 0, height = 0;
int pixelComponents = 0;

IntPtr ptr = ImageReader.GetImage(path, ref width, ref height, ref pixelComponents);

if (ptr == IntPtr.Zero) throw new Exception("Error loading image");


TextureFormat format = ImageReader.FormatFromPixelComponents(pixelComponents);

tex = new Texture2D(width, height, format, false);

tex.LoadRawTextureData(ptr, width * height * pixelComponents);
tex.Apply(); // Sends texture to GPU

Later in the C#, I am using ImageReader.FreeImage(IntPtr data) which just calls stbi_image_free(unsigned char* data) in c++.

Most importantly, I just need to make sure the image in memory won't get overwritten by something in c#.

Thanks for any advice!

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744286888a4566841.html

相关推荐

  • Will memory allocated in a c++ DLL be recognized by c# - Stack Overflow

    I can't figure out a good way to word this question since I'm kind of new to c++, but I found

    7天前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信