views:

30

answers:

1

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?

+2  A: 

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);
Dan Bryant
Ahhh that worked. Thanks. I was a bit fuzzy on that flag.
Adam Driscoll
The disclaimer in the documentation is a bit subtle. It clearly points out that you may leak memory if you pass false, but only further down does it clarify that if the structure does not contain valid data, then passing true will fail. Essentially it tries to free the memory pointed to by the string reference in the structure, but the pointer is invalid and, voila, a crash.
Dan Bryant