Re: Marshaling Delegates as Struct/Class Members
- From: "Nicholas Paldino [.NET/C# MVP]" <mvp@xxxxxxxxxxxxxxxxxxxxxxxxxxx>
- Date: Sat, 15 Oct 2005 10:38:25 -0400
Bob,
Yes, this is. See my reply to your initial post for why.
--
- Nicholas Paldino [.NET/C# MVP]
- mvp@xxxxxxxxxxxxxxxxxxxxxxxxxxx
"Bob" <nobody@xxxxxxxxxxx> wrote in message
news:OOTqPaW0FHA.1924@xxxxxxxxxxxxxxxxxxxxxxx
> 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
>>
>>
>
>
.
- References:
- Prev by Date: Re: String Operation in C#
- Next by Date: Re: String Operation in C#
- Previous by thread: Re: Marshaling Delegates as Struct/Class Members
- Next by thread: Re: Marshaling Delegates as Struct/Class Members
- Index(es):
Relevant Pages
|