问题描述
似乎在c#中我们应该使用Collection来避免使用动态数组。
但是,我现在使用C#通过托管C ++层在本机C ++中使用一些非托管代码并遇到问题在这里。
在我的C ++代码中,我有一个loadFile函数:
loadFile(const char * filename,byte * buffer)
将文件内容加载到缓冲区中。
我必须使用此函数来加载文件,因为它是压缩和加密的。
我无法修改本机c ++的代码。
我用这种方法加载文件:
在c#:
It seems that in c# we should use Collection to avoid using dynamic array.
However, I am now using C# to use some unmanaged code in native C++ through a Managed C++ layer and encountered a problem here.
In my C++ code I have a loadFile function:loadFile(const char* filename, byte* buffer)
which load the file content into the buffer.
I must use this function to load the file since it is compressed and encrypted.
I can't modify the code of the native c++.
I use this approach to load the file:
In c#:
ManagedDataFile DataFile = new ManagedDataFile(@"myPath");
DataFile.openDataFile();
byte[] filebuf = new byte[1024*30];
managedDataFile.loadFile(@"MyFileName", ref filebuf);
然而,我无法控制内存分配缓冲区filebuf。
有人可以根据我的情况提出建议吗?
非常感谢!
However, I can't control the memory allocation of the buffer "filebuf".
Can anyone suggest idea(s) for my situation?
Thanks a lot!
推荐答案
IntPtr fileData_ptr = IntPtr.Zero;
try
{
managedDataFile.loadFile(@"MyFileName", fileData_ptr);
if (fileData_ptr != IntPtr.Zero)
{
IntPtr pData = managedDataFile.GlobalLock(fileData_ptr);
IntPtr pArrayLocation = pData;
Int32 uiSize = Marshal.ReadInt32(pData);
byte[] filebuf = new byte[uiSize];
Marshal.Copy(pArrayLocation, filebuf, 0, uiSize);
managedDataFile.GlobalUnlock(pData);
managedDataFile.GlobalFree(fileData_ptr);
}
}
catch
{
}
这篇关于C#中的动态内存分配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!