C struct of delegates is clobbered when one is called

I'm passing a struct containing delegates to an native call in a DLL that wants a struct full of function pointers. The values it receives are all valid. However, when execution returns to the native DLL from the managed method (which runs flawlessly), all the members of native struct seem to get clobbered.

What I can't figure out is whether this is because they're all getting garbage collected, or I mixed up the calling conventions somewhere. Here's what happens to the native struct before and after it calls into the managed code:

a struct containing 4 pristine function pointers:

0x00198568003421ca

0x0019856C00342352

0x0019857000342392

0x00198574003423d2

Afterwards, all 4 members are clobbered, and the word immediately following the struct contains the address of the beginning of the struct.

0x0019856800198428

0x0019856C000000c8

0x0019857000000001

0x0019857400000000

0x0019857800198568

In short, the memory containing a C struct with 4 pointers into managed code turns into what looks like something from the stack after one of the function pointers is called. It's worth bringing up the fact that my DLL uses cdecl.

I've tried adding GCHandles to the C# struct, and also to each of the delegates it contains. I've also tried declaring the delegate types used in the struct with the attribute UnmanagedFunctionPointer(CallingConvention.Cdecl). None of which made any difference.

Does anyone have any other ideas?

[2359 byte] By [PeterN.] at [2008-1-2]
# 1

I don't believe you can directly pass a delegate to unmanaged code. Use the Marshal.GetFunctionPointerForDelegate to convert a delegate to a callable unmanaged function pointer.

Michael Taylor - 4/16/07

http://p3net.mvps.org

TaylorMichaelL at 2007-9-13 > top of Msdn Tech,Visual C#,Visual C# Language...
# 2

That actually worked a lot better.

The Callback sample in the MSDN library shows passing delegates directly to unmanaged code. The delegates did seem to be converted properly in my old code until they all vanished.

Thanks!

PeterN. at 2007-9-13 > top of Msdn Tech,Visual C#,Visual C# Language...