I'm trying to create a DynamicMethod to handle custom marshaling from a
pointer in memory to managed types. I'm trying to use a DynamicMethod so I
can template the code for all the custom marshaling and dont have to maintain
it.
My problem is I cant call Marshal.PtrToStructure in a DynamicMethod. I get
no exception, the method just exits. Its really odd. I've put debugging
WriteLine lines in my IL to find exactly what opcode was causing the problem,
and its the 10th opcode (shown below). It gets to that point, and then
"poof" (and I dont even believe in poofs in computers, but I cant explain it)
I then dumped my IL to an assembly (via reflection.enit) and opened it in
Reflector and compared it to the IL that the C# compiler created from my C#
code that does this. and its EXACTLY the same. I mean the IL for the entire
method is EXACTLY the same.
Does anyone have an idea? Below is the method def and the first 12 or so
opcodes, taken from Reflector.
One other thing; the C# method that I based this IL code from is marked as
unsafe, but I didnt see anything in Reflection.Emit to mark something as
unsafe.
.method public hidebysig virtual instance void
SetTraceData_ProcessEventData(void* pData, int32 length) cil managed
{
.maxstack 15
.locals init (
[0] int32 num,
[1] native int ptr,
[2] int32 num2,
[3] bool flag)
ldc.i4.0
stloc.0
ldloca.s ptr
ldarg.2
call instance void [mscorlib]System.IntPtr::.ctor(void*)
ldarg.1
ldloc.1
ldtoken int32
call class [mscorlib]System.Type
[mscorlib]System.Type::GetTypeFromHandle(valuetype
[mscorlib]System.RuntimeTypeHandle)
call object
[mscorlib]System.Runtime.InteropServices.Marshal::PtrToStructure(native int,
class [mscorlib]System.Type)
unbox.any int32
stfld int32
[Attenex.Instrumentation]Attenex.Instrumentation.Etw.ProcessEventData::instanceId
.
.
.
ret
}
john conwell - 28 Nov 2007 18:22 GMT
oh buggers, I figured it out. I actually was emmitting one wrong IL opcode.
the 4th opcode was "ldarg.2", and should have been "ldarg.1". Basically I
was trying to marshal data from a pointer in memory to the wrong place, where
my process didnt own. This caused badness.
I guess it goes to show how easy it is to screw up IL emittion :-)
> I'm trying to create a DynamicMethod to handle custom marshaling from a
> pointer in memory to managed types. I'm trying to use a DynamicMethod so I
[quoted text clipped - 51 lines]
> ret
> }
Günter Prossliner - 29 Nov 2007 08:19 GMT
Hello John!
> I then dumped my IL to an assembly (via reflection.enit) and opened
> it in Reflector and compared it to the IL that the C# compiler
> created from my C# code that does this.
If you do all this just to view the IL of the DynamicMethod, you should take
a look at this:
[Haibo Luo's weblog : DebuggerVisualizer for DynamicMethod (Show me the IL)]
http://blogs.msdn.com/haibo_luo/archive/2005/10/25/484861.aspx
GP