B
Bob
I understand delegates do not need to be pinned, but its the class object
itself I need pinned. Take this code:
[StructLayout(LayoutKind.Sequential)]
public class TestObject
{
[MarshalAs(UnmanagedType.FunctionPtr)]
public AddDelegate Add;
[MarshalAs(UnmanagedType.FunctionPtr)]
public SubtractDelegate Subtract;
public delegate Int32 AddDelegate(Int32 a, Int32 b);
public delegate Int32 SubtractDelegate(Int32 a, Int32 b);
}
public class Program
{
private static void Main(
String[] args)
{
TestObject testObject = new TestObject();
GCHandle gcHandle = GCHandle.Alloc(testObject,
GCHandleType.Pinned);
}
}
The GCHandle.Alloc fails with:
System.ArgumentException was unhandled
Message="Object contains non-primitive or non-blittable data."
Source="mscorlib"
StackTrace:
at System.Runtime.InteropServices.GCHandle.InternalAlloc(Object
value, GCHandleType type)
at System.Runtime.InteropServices.GCHandle.Alloc(Object value,
GCHandleType type)
Is there an easy way to marshal delegates as part of a struct? Isn't that
what UnmanagedType.FunctionPtr is for? I don't want to manage multiple
objects and manually marshal stuff using
Marshal.GetFunctionPointerForDelegate? I -really- want to avoid that route
in this particular project.
Thanks
itself I need pinned. Take this code:
[StructLayout(LayoutKind.Sequential)]
public class TestObject
{
[MarshalAs(UnmanagedType.FunctionPtr)]
public AddDelegate Add;
[MarshalAs(UnmanagedType.FunctionPtr)]
public SubtractDelegate Subtract;
public delegate Int32 AddDelegate(Int32 a, Int32 b);
public delegate Int32 SubtractDelegate(Int32 a, Int32 b);
}
public class Program
{
private static void Main(
String[] args)
{
TestObject testObject = new TestObject();
GCHandle gcHandle = GCHandle.Alloc(testObject,
GCHandleType.Pinned);
}
}
The GCHandle.Alloc fails with:
System.ArgumentException was unhandled
Message="Object contains non-primitive or non-blittable data."
Source="mscorlib"
StackTrace:
at System.Runtime.InteropServices.GCHandle.InternalAlloc(Object
value, GCHandleType type)
at System.Runtime.InteropServices.GCHandle.Alloc(Object value,
GCHandleType type)
Is there an easy way to marshal delegates as part of a struct? Isn't that
what UnmanagedType.FunctionPtr is for? I don't want to manage multiple
objects and manually marshal stuff using
Marshal.GetFunctionPointerForDelegate? I -really- want to avoid that route
in this particular project.
Thanks