我有一个c ++ dll,它为我的主要c#应用程序提供一些功能.在这里,我尝试读取文件,将其加载到内存,然后将一些信息(如指针加载数据和内存块计数)返回到c#.Dll成功将文件读取到内存,但在返回主应用程序时,程序因堆损坏而崩溃(检测到严重错误c0000374).
代码非常简单明了,之前我做过类似的事情没有问题,但是我无法弄清楚是什么原因导致问题,我尝试使用"new,malloc和GlobalAlloc"分配内存,但都没有帮助.代码如下:
C++ MyDll:
typedef unsigned long U32; extern "C" __declspec(dllexport) int ReadFile(LPSTR Path, U32** DataPtr, U32* Count) { FILE *fp; U32 *Data; CString tempStr(Path); long fSize; if(!(fp = fopen(tempStr, "rb"))) { return 0; } // Obtain File Size; fseek(fp, 0, SEEK_END); fSize = ftell(fp); rewind(fp); Data = (U32 *)GlobalAlloc(0, fSize); if(Data == NULL) { fclose(fp); return -1; } // Copy file into the buffer. if(!(*Count = fread(Data, sizeof(U32), fSize / sizeof(U32), fp))) { fclose(fp); free(Data); return -2; } *DataPtr = (U32 *)Data; return 1; }
C#应用:
[DllImport(@"MyDll.dll", CallingConvention= CallingConvention.Cdecl)] private static extern int ReadFile([MarshalAs(UnmanagedType.LPStr)]string Path, out IntPtr dataPtr, out uint Count); private void readDump(string Path) { uint count = 0; IntPtr Data = new IntPtr(); try{ if(ReadFile(Path, out Data, out count) == 1) //The Program crashes just right after this statement { //Do Something ... } } catch() {} }
程序在调试和释放模式下崩溃.除非我在加载文件后在调试模式下暂停程序并在"Visual Studio的立即窗口"中调用一些内存块.要加载的文件大小约为64MB,我们在PC上有超过2GB未使用的RAM.
更新:我注意到,他们之前工作的一些第三方程序崩溃了"异常代码:c0000005",还有一些其他奇怪的事情发生在Windows 7(主机)中.所以我在另一个Windows安装中测试了代码,一切看起来都像他们应该的那样工作.所以它可能与Windows 7有关.现在我该如何解决这个问题呢?"sfc/scannow"找不到任何问题.