Calling unmanaged dll code from C++/CLI code throws SEHException immediately on any function call

36 Views Asked by At

I have the simplest possible unmanaged test dll that I just cannot call methods from using C++/CLI dll. I have the following code in the NativeDll project:

//TestFunctions.h
#pragma once

#ifdef NATIVEDLL_EXPORTS
#define NATIVE_FUNCTIONS_API __declspec(dllexport)
#else
#pragma comment(lib,"NativeDll.lib")
#define NATIVE_FUNCTIONS_API __declspec(dllimport)
#endif


extern "C" NATIVE_FUNCTIONS_API int test_function1();
extern "C" NATIVE_FUNCTIONS_API int test_function2();

Cpp file for the methods in the NativeDll project:

#include "TestFunctions.h"

int test_function1()
{
    return 1;
}
int test_function2()
{
    return 2;
}

In the calling C++/CLI CompatLayer dll project I'm calling the methods as follows:

//Compatibility.h
#pragma once

namespace CompatLayer {
    public ref class Compatibility
    {
    public:
        static void Initialize();
        static int f1();
        static int f2();
    };

}

Cpp file:

#include "Compatibility.h"
#include <TestFunctions.h>
#include <string>
#include <iostream>
#include <msclr\marshal_cppstd.h>

void CompatLayer::Compatibility::Initialize()
{
    std::cout << "Hello from compat layer init function!" << std::endl;
}

int CompatLayer::Compatibility::f1()
{
    try {
        std::cout << "Compat layer: Calling unmanaged code" << std::endl;//Prints fine
        return test_function1();
    }
    catch (System::Runtime::InteropServices::SEHException^ e) {//We always get SEHException
        std::cout << "SEHException thrown when calling unmanaged code" << std::endl;
        System::String^ msg = e->ToString();
        std::cout << msclr::interop::marshal_as<std::string>(msg) << std::endl;
    }
    catch (std::exception e) {
        std::cout << "std::exception thrown when executing code" << std::endl;
        std::cout << e.what() << std::endl;
    }
    return -1;
}

We are always getting the SEHException in the catch block in the C++/CLI code. The code in the NativeDLL project does not throw so I'm pretty much out of ideas where that exception could originate. Also the exception output isn't that useful:

SEHException thrown when calling unmanaged code
External component has thrown an exception.
System.Runtime.InteropServices.SEHException (0x80004005): External component has thrown an exception.
   at test_function1()

What could be causing this exception? It seems like the unmanaged code never gets invoked. Target .NET Framework is 4.0 and the native dll is marked as delay loading in the C++/CLI adapator dll.

0

There are 0 best solutions below