Re: Marshaling Delegates as Struct/Class Members
- From: "Bob" <nobody@xxxxxxxxxxx>
- Date: Sat, 15 Oct 2005 01:58:00 -0700
Furthermore, why can I marshal this class but I can't pin it?
Int32 size = Marshal.SizeOf(typeof(TestObject));
IntPtr ptr = Marshal.AllocCoTaskMem(size);
Marshal.StructureToPtr(testObject, ptr, false);
Marshal.FreeCoTaskMem(ptr);
I would think anything on the managed heap that can be marshalled could be
pinned. Is this wrong?
Thanks
"Bob" <nobody@xxxxxxxxxxx> wrote in message
news:eQx8nST0FHA.3720@xxxxxxxxxxxxxxxxxxxxxxx
>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
>
>
.
- Follow-Ups:
- Re: Marshaling Delegates as Struct/Class Members
- From: Nicholas Paldino [.NET/C# MVP]
- Re: Marshaling Delegates as Struct/Class Members
- Prev by Date: Re: Sniffing Network Data
- Next by Date: Re: SQL updates on MS Access Database: error: Operation must use an updateable query.
- Previous by thread: Probability Distribution Library
- Next by thread: Re: Marshaling Delegates as Struct/Class Members
- Index(es):
Relevant Pages
|