C#中的动态内存分配? [英] Dynamic Memory Allocation in C#?

查看:113
本文介绍了C#中的动态内存分配?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

似乎在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!

推荐答案

编写一个托管C ++方法,它返回文件的大小。
Write a managed C++ method which returns the size of the file.


您可能需要查看 System.Runtime中可用的函数。 InteropServices.Marshal 类,看看它们是否有用。

查看这篇文章 [ ^ ]它可能对您的要求有所帮助。



不确定这是否有效,但你可以试试这个;

You may want to look at the functions available in the System.Runtime.InteropServices.Marshal class and see if any of them may be of use.
Take a look at this article[^] it may help with your requirement.

Not sure if this will work but you could try this;
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#中的动态内存分配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆