Unexpected Stackoverflow exception using CLR in a

2019-09-06 00:11发布

问题:

I have a software that accepts a C dll as plugin. The dll export two functions: init and quit. To test how the plugin works, I wrote three projects after the NativeWrapper concept: a managed library in C++ (dll), a native wrapper in C++ (also dll, that exports the init and quit functions) and a C++ test program. For now I am just testing the init function.

All these are built and run inside VS 2013 without any issue. However, When I plug the two dlls in with the said software, it stops working and throws a stackoverflow exception. I understand that the most likely cause of stackoverflow exception is infinite loop or recursion. But I have neither in my codes. Does anyone have any clue? If I remove the interop call line:

ManagedLib::ManagedClass::SayHello()

then the dll has no problem running as a plugin. In this case, it only output to the console once, which tells me that there is no looping or recursion in the calling software.

BTW, I have to point out that the software has been out for years. So I am not sure if the problem comes from the difference in development environments used (framework 4.5 vs ???)

Managedlib.h:

#pragma once

namespace ManagedLib
{

public ref class ManagedClass
{
public:
  static void SayHello();
};

}

Managedlib.cpp

#include "stdafx.h"

#include "ManagedLib.h"

using namespace System;

using namespace ManagedLib;

void ManagedClass::SayHello()
{
  Console::WriteLine("Hello from the managed world!");
  Console::Out->Flush();
}

Nativewrapper.h:

#pragma once

#include <Windows.h>

#undef __cplusplus
#ifdef __cplusplus
extern "C"
{
#endif

  //EXPORTS 
    int WINAPI Init(HWND hwnd, UINT, int);
    int WINAPI Quit(HWND hwnd);
#ifdef __cplusplus
}
#endif

Nativewrapper.cpp:

#include "stdafx.h"
#include <stdio.h>

#define BUILDING_WRAPPER_DLL

#include "NativeWrapper.h"

int WINAPI Init(HWND hwnd, UINT32, int)
{

    FILE * pConsole;
    AllocConsole();
    freopen_s(&pConsole, "CONOUT$", "wb", stdout);
    printf("Started\n");

    ManagedLib::ManagedClass::SayHello();
    return 1;
}

int WINAPI Quit(HWND hwnd)
{
    return 1;
}