How to break in c++ code called from c# interop

Viewed 169

Working with Visual Studio 2019. Calling c functions from c# is common but when there is a runtime error, I get a popup window as such:

runtime error

I would like however to actually break into the c++ code so I can debug it,in particular review the call stack, watch the local variables, add break points etc.

How to achieve this ?

If one need a demo project: https://github.com/mprevot/InteropDemo

I'm calling a c function designed to fail:

#ifndef Pinvoke
#define Pinvoke extern "C" __declspec(dllexport)
#endif

std::wstring ToString(int number)
{
    std::wstringstream s;
    s << "got number " << number;
    return s.str();
}

Pinvoke auto GetNumbers() -> void
{
    std::vector<int> array0{11,12,13,14};
    std::vector<int> array1{21,22,23};
    for (size_t i = 0; i < 4; i++)
        ToString(array0[i]);
    for (size_t i = 0; i < 4; i++)
        ToString(array1[i]);
}

I call such function from c#:

internal static class NativeLibCall
{
    public const string _dll = "NativeLib.dll";

    [DllImport(_dll, CallingConvention = CallingConvention.StdCall)]
    internal static extern void GetNumbers();
}

public class NativeLibInterop
{
    public void GetNumbers() => NativeLibCall.GetNumbers();
}
1 Answers

As suggested by Kevin Gosse, and detailed in MSFT documentation, just enable mixed-mode debugging:

Enable mixed-mode debugging for a managed calling app

  1. Select the C# or Visual Basic project in Solution Explorer and select the Properties icon, press Alt+Enter, or right-click and choose Properties.

  2. Select the Debug tab, and then select Enable native code debugging.

  3. Close the properties page to save the changes.

Related