Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Marshal.StructureToPtr crashes Visual Studio

I'm working on a custom debug engine and when I marshal my structure to a IntPtr Visual Studio crashes (the one being debugged not the debugger).

My struct is little more than:

public struct DocumentContext : IDebugDocumentContext2, IDebugCodeContext2
{
    private string _fileName;

    //.....Implementation of interfaces
}

My marshalling code looks like this:

        var documentContext = new DocumentContext(_node.FileName);
        var size = Marshal.SizeOf(documentContext);
        IntPtr ptrDocContext = Marshal.AllocHGlobal(size);
        //This is what is crashing 
        //I don't have a chance to catch anything, it just craps out
        //Event log says faulting dll is nt.dll
        Marshal.StructureToPtr(documentContext, ptrDocContext, true); 

Am I missing something?

like image 885
Adam Driscoll Avatar asked Feb 08 '26 04:02

Adam Driscoll


1 Answers

You should not use deleteOld if the unmanaged structure was never previously allocated. deleteOld is only applicable when you're overwriting a previous structure (so as to deallocate string references, for example.) This should work:

Marshal.StructureToPtr(documentContext, ptrDocContext, false);
like image 71
Dan Bryant Avatar answered Feb 12 '26 06:02

Dan Bryant



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!