最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin6浏览0评论

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!

发布评论

评论列表(0)

  1. 暂无评论