在C#中导出的C ++函数中分配内存时的访问冲突

时间:2016-07-20 10:01:54

标签: c# c++ pinvoke dllexport

我试图在C ++中为.NET开发人员准备一个简单的内存泄漏示例。因此,我创建了一个C ++ dll(带有gcc 4.9.2的DevC ++ 5.11),它是通过PInvoke从.NET Console应用程序调用的。这两个项目都是64位。我能够从.NET调用导出的方法,甚至返回值。但每当我使用new运算符时,都会引发Access违例异常。我开始变得疯狂,你能告诉我什么是错的吗?

C ++代码(我只有1个单独的文件dllmain.cpp,只包含这些行,没有其他内容):

extern "C" __declspec(dllexport) int CalculateRandomNumber()
{    
     int*ptr_one;
     //ptr_one = new int[1000000];    //<---Uncommenting this will generate AccessViolation
     return 4;
};

Compiler output is:
Compiling project changes...
--------
- Project Filename: D:\MemoryLeakPresentation\c++\SmartDll.dev
- Compiler Name: TDM-GCC 4.9.2 64-bit Release

Building makefile...
--------
- Filename: D:\MemoryLeakPresentation\c++\Makefile.win

Processing makefile...
--------
- Makefile Processor: C:\Program Files (x86)\Dev-Cpp\MinGW64\bin\mingw32-make.exe
- Command: mingw32-make.exe -f "D:\MemoryLeakPresentation\c++\Makefile.win" all

g++.exe -c dllmain.cpp -o dllmain.o -I"C:/Program Files (x86)/Dev-Cpp/MinGW64/include" -I"C:/Program Files (x86)/Dev-Cpp/MinGW64/x86_64-w64-mingw32/include" -I"C:/Program Files (x86)/Dev-Cpp/MinGW64/lib/gcc/x86_64-w64-mingw32/4.9.2/include" -I"C:/Program Files (x86)/Dev-Cpp/MinGW64/lib/gcc/x86_64-w64-mingw32/4.9.2/include/c++" -DBUILDING_DLL=1

g++.exe -shared dllmain.o -o SmartDll.dll -L"C:/Program Files (x86)/Dev-Cpp/MinGW64/lib" -L"C:/Program Files (x86)/Dev-Cpp/MinGW64/x86_64-w64-mingw32/lib" -static-libgcc -Wl,--output-def,libSmartDll.def,--out-implib,libSmartDll.a,--add-stdcall-alias


Compilation results...
--------
- Errors: 0
- Warnings: 0
- Output Filename: D:\MemoryLeakPresentation\c++\SmartDll.dll
- Output Size: 366.10546875 KiB
- Compilation Time: 0.23s

然后我像这样将它导入C#。我使用Visual Studio 2015 Complete程序如下所示:

class Program
{

    [DllImport(@"d:\MemoryLeakPresentation\c++\SmartDll.dll", CallingConvention = CallingConvention.Cdecl)]
    private static extern int CalculateRandomNumber();

    static void Main(string[] args)
    {
        for (int i = 0; i < 1000; i++)
        {
            int random =  CalculateRandomNumber();
            Console.WriteLine(random);
            Thread.Sleep(200);
        }
    }

}

老实说,我不知道发生了什么事,我也没有任何其他信息。在我取消注释内存分配的那一刻,它崩溃了:

1_CallingCppCode.exe中0x0000000068214620(SmartDll.dll)的未处理异常:0xC0000005:访问冲突读取位置0xFFFFFFFFCA161F1B。

0 个答案:

没有答案