I've done a fair amount of P/Invoking but for some reason I'm having problem with this one case. I need to define a delegate because I need to dynamically create the delegate at runtime using Marshal.GetDelegateForFunctionPointer(). Anyway, I don't think that is directly related to my problem, it is more to do with how I declare the delegate and use it. So say I have this:
[StructLayout(LayoutKind.Sequential, Pack = 4)]
public struct MyStruct
{
public bool Value1;
public int Value2;
public IntPtr Ptr1;
public IntPtr Ptr2;
}
[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
public delegate void Foo([MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)]
ref MyStruct[] structs, int arrayLength);Note that the structs array is both in and out, so I need to use ref (the native method modifies the structures). Now when I do this:
var structs = new MyStruct[10];
for (var idx = 0; idx < structs.Length; idx++)
{
structs[idx].Value2 = idx;
....
}
Foo(ref structs, structs.Length);...The call fails. Note I simplified the code in this example but in the real code the function returns a value indicating failure.
Now if I change the delegate declaration and the way I call it to the following...
[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
public delegate void Foo(IntPtr structs, int arrayLength);
fixed (MyStruct* pStructs = &structs[0])
{
Foo(pStructs, structs.Length);
}The call succeeds. It seems that the two should be the same from the native code's perspective. I would prefer if I don't have to use unsafe methods and the need to mark the assembly as using unsafe code. So what is wrong with my 1st delegate declaration?
Thread Closed
This thread is kinda stale and has been closed but if you'd like to continue the conversation, please create a new thread in our Forums,
or Contact Us and let us know.