我有一个 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。
UPDATE:我注意到,他们之前运行的一些第三方程序崩溃并显示“异常代码:c0000005”,并且 Windows 7(主机)中还发生了一些其他奇怪的事情。所以我在另一个 Windows 安装中测试了代码,一切似乎都按预期工作。所以可能与 Windows 7 有关。现在我该如何解决这个问题? “sfc /scannow”未能发现任何问题。