How to attach debugger to step into native (C++) code from a managed (C#) wrapper?
Asked Answered
S

4

20

I have a wrapper around a C++ function call which I call from C# code. How do I attach a debugger in Visual Studio to step into the native C++ code?

This is the wrapper that I have which calls GetData() defined in a C++ file:

    [DllImport("Unmanaged.dll", CallingConvention=CallingConvention.Cdecl, 
               EntryPoint = "GetData", BestFitMapping = false)]
        public static extern String GetData(String url);

The code is crashing and I want to investigate the root cause.

Thanks, Nikhil

Sectorial answered 11/9, 2008 at 22:45 Comment(0)
A
23

Check the Debug tab on your project's properties page. There should be an "Enable unmanaged code debugging" checkbox. This worked for me when we developed a new .NET UI for our old c++ DLLs.

If your unmanaged DLL is being built from another project (for a while ours were being built using VS6) just make sure you have the DLL's pdb file handy for the debugging.

The other approach is to use the C# exe as the target exe to run from the DLL project, you can then debug your DLL normally.

Amative answered 11/9, 2008 at 23:2 Comment(0)
S
9

in addition to Lou's advise for starting the debugger, you can select which debug engines are used when attaching to an existing process by clicking on 'Select...' in the 'attach to process' dialog and choosing both 'managed code' and 'native code'.

Debugging in this way is called mixed mode debugging. See this blog post for some tips.

I believe this isn't supported for 64 bit processes ... though would love to be wrong on that point.

Savoirvivre answered 11/9, 2008 at 23:10 Comment(1)
Thanks for the follow-up. I don't tend to use "attach to process" so I forget that it's another option. cheers.Amative
A
2

To anyone using WinDbg:

1>Setup symbols

Look at these commands. (Help: in console .hh < command> )

.sympath
.sympath+ 
.symfix

2>Set up source path

.srcpath

3>Load SOS extention to debug managed / mixed mode programs.

(Make sure you have extention path setup correctly)

Add Microsoft.NET\Framework\v2.0.50727 for x86 using-

.extpath 

Set a breakpoint for the clr to load.

sxe ld:mscorwks

(F5 / g) (Wait for ModLoad BP on mscorwks.dll)

Make sure you dont have a duplicate sos extention already loaded. See:

.chain

Now we're ready to load the sos extention. :)

.loadby sos mscorwks

4> Reload all the symbols..

.reload

Now you're all set :)

(YMMV)

Alexandretta answered 12/9, 2008 at 13:29 Comment(0)
G
2

Mixed debugging is not supported in 64bit mode (as of Visual Studio 2008).

Garnishee answered 8/4, 2009 at 22:47 Comment(1)
Could you post any articles that you may have on this subject?Service

© 2022 - 2024 — McMap. All rights reserved.