-
Notifications
You must be signed in to change notification settings - Fork 107
/
Copy pathWinRT_Wrappers.cs
639 lines (555 loc) · 25.1 KB
/
WinRT_Wrappers.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Numerics;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Linq.Expressions;
using WinRT.Interop;
#pragma warning disable 0169 // The field 'xxx' is never used
#pragma warning disable 0649 // Field 'xxx' is never assigned to, and will always have its default value
namespace WinRT
{
public static partial class ComWrappersSupport
{
private readonly static ConcurrentDictionary<string, Func<IInspectable, object>> TypedObjectFactoryCache = new ConcurrentDictionary<string, Func<IInspectable, object>>();
private readonly static IReadOnlyDictionary<string, string> TypeMappings;
static ComWrappersSupport()
{
// Make sure to keep this consistent with the table in helpers.h
TypeMappings = new Dictionary<string, string>
{
{ "Windows.Foundation.DateTime", "System.DateTimeOffset" },
{ "Windows.Foundation.TimeSpan", "System.TimeSpan" }
};
}
public static TReturn MarshalDelegateInvoke<TDelegate, TReturn>(IntPtr thisPtr, Func<TDelegate, TReturn> invoke)
where TDelegate : class, System.Delegate
{
using (new Mono.ThreadContext())
{
var target_invoke = FindDelegate<TDelegate>(thisPtr);
if (target_invoke != null)
{
return invoke(target_invoke);
}
return default;
}
}
public static void MarshalDelegateInvoke<T>(IntPtr thisPtr, Action<T> invoke)
where T : class, System.Delegate
{
using (new Mono.ThreadContext())
{
var target_invoke = FindDelegate<T>(thisPtr);
if (target_invoke != null)
{
invoke(target_invoke);
}
}
}
internal static List<ComInterfaceEntry> GetInterfaceTableEntries(object obj)
{
var entries = new List<ComInterfaceEntry>();
var interfaces = obj.GetType().GetInterfaces();
foreach (var iface in interfaces)
{
if (iface == typeof(WinRT.IWeakReference))
{
entries.Add(new ComInterfaceEntry
{
IID = typeof(WinRT.Interop.IWeakReferenceVftbl).GUID,
Vtable = WinRT.Interop.IWeakReferenceVftbl.AbiToProjectionVftablePtr
});
continue;
}
var ifaceAbiType = iface.Assembly.GetType("ABI." + iface.FullName);
if (ifaceAbiType == null)
{
// This interface isn't a WinRT interface.
// TODO: Handle WinRT -> .NET projected interfaces.
continue;
}
entries.Add(new ComInterfaceEntry
{
IID = GuidGenerator.GetIID(ifaceAbiType),
Vtable = (IntPtr)ifaceAbiType.GetNestedType("Vftbl").GetField("AbiToProjectionVftablePtr", BindingFlags.Public | BindingFlags.Static).GetValue(null)
});
}
entries.Add(new ComInterfaceEntry
{
IID = typeof(WinRT.Interop.IWeakReferenceSourceVftbl).GUID,
Vtable = WinRT.Interop.IWeakReferenceSourceVftbl.AbiToProjectionVftablePtr
});
return entries;
}
internal static (InspectableInfo inspectableInfo, List<ComInterfaceEntry> interfaceTableEntries) PregenerateNativeTypeInformation(object obj)
{
string typeName = obj.GetType().FullName;
if (typeName.StartsWith("ABI.")) // If our type is an ABI type, get the real type name
{
typeName = typeName.Substring("ABI.".Length);
}
var interfaceTableEntries = GetInterfaceTableEntries(obj);
var iids = new Guid[interfaceTableEntries.Count];
for (int i = 0; i < interfaceTableEntries.Count; i++)
{
iids[i] = interfaceTableEntries[i].IID;
}
return (
new InspectableInfo(typeName, iids),
interfaceTableEntries);
}
internal static Func<IInspectable, object> CreateTypedRcwFactory(string runtimeClassName)
{
var (implementationType, _) = FindTypeByName(runtimeClassName.AsSpan());
Type classType;
Type interfaceType;
Type vftblType;
if (implementationType.IsInterface)
{
classType = null;
interfaceType = FindTypeByName(("ABI." + runtimeClassName).AsSpan()).type ??
throw new TypeLoadException($"Unable to find an ABI implementation for the type '{runtimeClassName}'");
vftblType = interfaceType.GetNestedType("Vftbl") ?? throw new TypeLoadException($"Unable to find a vtable type for the type '{runtimeClassName}'");
if (vftblType.IsGenericTypeDefinition)
{
vftblType = vftblType.MakeGenericType(interfaceType.GetGenericArguments());
}
}
else
{
classType = implementationType;
interfaceType = classType.GetField("_default", BindingFlags.Instance | BindingFlags.NonPublic)?.FieldType;
if (interfaceType is null)
{
throw new TypeLoadException($"Unable to create a runtime wrapper for a WinRT object of type '{runtimeClassName}'. This type is not a projected type.");
}
vftblType = interfaceType.GetNestedType("Vftbl") ?? throw new TypeLoadException($"Unable to find a vtable type for the type '{runtimeClassName}'");
}
ParameterExpression[] parms = new[] { Expression.Parameter(typeof(IInspectable), "inspectable") };
var createInterfaceInstanceExpression = Expression.New(interfaceType.GetConstructor(new[] { typeof(ObjectReference<>).MakeGenericType(vftblType) }),
Expression.Call(parms[0],
typeof(IInspectable).GetMethod(nameof(IInspectable.As)).MakeGenericMethod(vftblType)));
if (classType is null)
{
return Expression.Lambda<Func<IInspectable, object>>(createInterfaceInstanceExpression, parms).Compile();
}
return Expression.Lambda<Func<IInspectable, object>>(
Expression.New(classType.GetConstructor(BindingFlags.NonPublic | BindingFlags.CreateInstance | BindingFlags.Instance, null, new[] { interfaceType }, null),
createInterfaceInstanceExpression),
parms).Compile();
}
private static (Type type, int remaining) FindTypeByName(ReadOnlySpan<char> runtimeClassName)
{
var (genericTypeName, genericTypes, remaining) = ParseGenericTypeName(runtimeClassName);
return (FindTypeByNameCore(genericTypeName, genericTypes), remaining);
}
private static Type FindTypeByNameCore(string runtimeClassName, Type[] genericTypes)
{
// TODO: This implementation is a strawman implementation.
// It's missing support for types not loaded in the default ALC.
if (TypeMappings.TryGetValue(runtimeClassName, out string mappedClassName))
{
return FindTypeByNameCore(mappedClassName, genericTypes);
}
if (genericTypes is null)
{
Type primitiveType = ResolvePrimitiveType(runtimeClassName);
if (primitiveType is object)
{
return primitiveType;
}
}
foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
{
Type type = assembly.GetType(runtimeClassName);
if (type is object)
{
if (genericTypes != null)
{
type = type.MakeGenericType(genericTypes);
}
return type;
}
}
throw new TypeLoadException($"Unable to find a type named '{runtimeClassName}'");
}
private static Type ResolvePrimitiveType(string primitiveTypeName)
{
return primitiveTypeName switch
{
"UInt8" => typeof(byte),
"Int8" => typeof(sbyte),
"UInt16" => typeof(ushort),
"Int16" => typeof(short),
"UInt32" => typeof(uint),
"Int32" => typeof(int),
"UInt64" => typeof(ulong),
"Int64" => typeof(long),
"Boolean" => typeof(bool),
"String" => typeof(string),
"Char" => typeof(char),
"Single" => typeof(float),
"Double" => typeof(double),
"Guid" => typeof(Guid),
"Object" => typeof(object),
_ => null
};
}
private static (string genericTypeName, Type[] genericTypes, int remaining) ParseGenericTypeName(ReadOnlySpan<char> partialTypeName)
{
int possibleEndOfSimpleTypeName = partialTypeName.IndexOfAny(new[] { ',', '>' });
int endOfSimpleTypeName = partialTypeName.Length;
if (possibleEndOfSimpleTypeName != -1)
{
endOfSimpleTypeName = possibleEndOfSimpleTypeName;
}
var typeName = partialTypeName.Slice(0, endOfSimpleTypeName);
if (!typeName.Contains("`".AsSpan(), StringComparison.Ordinal))
{
return (typeName.ToString(), null, endOfSimpleTypeName);
}
int genericTypeListStart = partialTypeName.IndexOf('<');
var genericTypeName = partialTypeName.Slice(0, genericTypeListStart);
var remaining = partialTypeName.Slice(genericTypeListStart + 1);
int remainingIndex = genericTypeListStart + 1;
List<Type> genericTypes = new List<Type>();
while (true)
{
var (genericType, endOfGenericArgument) = FindTypeByName(remaining);
remainingIndex += endOfGenericArgument;
genericTypes.Add(genericType);
remaining = remaining.Slice(endOfGenericArgument);
if (remaining[0] == ',')
{
// Skip the comma and the space in the type name.
remainingIndex += 2;
remaining = remaining.Slice(2);
continue;
}
else if (remaining[0] == '>')
{
break;
}
else
{
throw new InvalidOperationException("The provided type name is invalid.");
}
}
return (genericTypeName.ToString(), genericTypes.ToArray(), partialTypeName.Length - remaining.Length);
}
internal class InspectableInfo
{
public readonly string RuntimeClassName;
public readonly Guid[] IIDs;
internal InspectableInfo(string runtimeClassName, Guid[] iids)
{
RuntimeClassName = runtimeClassName;
IIDs = iids;
}
}
}
#if MANUAL_IUNKNOWN
public static partial class ComWrappersSupport
{
private static ConditionalWeakTable<object, ComCallableWrapper> ComWrapperCache = new ConditionalWeakTable<object, ComCallableWrapper>();
private static ConditionalWeakTable<object, Delegate> DelegateWrapperCache = new ConditionalWeakTable<object, Delegate>();
private static ConcurrentDictionary<IntPtr, WeakReference<object>> RuntimeWrapperCache = new ConcurrentDictionary<IntPtr, WeakReference<object>>();
internal static InspectableInfo GetInspectableInfo(IntPtr pThis) => UnmanagedObject.FindObject<ComCallableWrapper>(pThis).InspectableInfo;
public static object CreateRcwForComObject(IntPtr ptr)
{
if (ptr == IntPtr.Zero)
{
return null;
}
IObjectReference identity = ObjectReference<IUnknownVftbl>.FromAbi(ptr).As<IUnknownVftbl>();
object keepAliveSentinel = null;
Func<IntPtr, IObjectReference, WeakReference<object>> rcwFactory = (_, objRef) =>
{
var inspectable = new IInspectable(objRef);
string runtimeClassName = inspectable.GetRuntimeClassName();
var runtimeWrapper = TypedObjectFactoryCache.GetOrAdd(runtimeClassName, className => CreateTypedRcwFactory(className))(inspectable);
keepAliveSentinel = runtimeWrapper; // We don't take a strong reference on runtimeWrapper at any point, so we need to make sure it lives until it can get assigned to rcw.
var runtimeWrapperReference = new WeakReference<object>(runtimeWrapper);
var cleanupSentinel = new RuntimeWrapperCleanup(identity.ThisPtr, runtimeWrapperReference);
return runtimeWrapperReference;
};
RuntimeWrapperCache.AddOrUpdate(
identity.ThisPtr,
rcwFactory,
(ptr, oldValue, objRef) =>
{
if (!oldValue.TryGetTarget(out keepAliveSentinel))
{
return rcwFactory(ptr, objRef);
}
return oldValue;
},
identity).TryGetTarget(out object rcw);
GC.KeepAlive(keepAliveSentinel);
return rcw;
}
public static void RegisterObjectForInterface(object obj, IntPtr thisPtr)
{
var referenceWrapper = new WeakReference<object>(obj);
var _ = new RuntimeWrapperCleanup(thisPtr, referenceWrapper);
RuntimeWrapperCache.TryAdd(thisPtr, referenceWrapper);
}
public static IObjectReference CreateCCWForObject(object obj)
{
if (obj is global::System.Delegate del)
{
return (IObjectReference)del.GetType().GetHelperType().GetMethod("CreateMarshaler").Invoke(null, new object[] { del });
}
var wrapper = ComWrapperCache.GetValue(obj, _ => new ComCallableWrapper(obj));
var objRef = ObjectReference<IUnknownVftbl>.FromAbi(wrapper.IdentityPtr);
GC.KeepAlive(wrapper); // This GC.KeepAlive ensures that a newly created wrapper is alive until objRef is created and has AddRef'd the CCW.
return objRef;
}
public static IObjectReference CreateCCWForDelegate(global::System.Delegate abiInvoke, global::System.Delegate del)
{
var wrapper = DelegateWrapperCache.GetValue(del, _ => new Delegate(abiInvoke, del));
var objRef = ObjectReference<IDelegateVftbl>.FromAbi(wrapper.ThisPtr);
GC.KeepAlive(wrapper); // This GC.KeepAlive ensures that a newly created wrapper is alive until objRef is created and has AddRef'd the CCW.
return objRef;
}
public static T FindObject<T>(IntPtr thisPtr)
where T : class =>
(T)UnmanagedObject.FindObject<ComCallableWrapper>(thisPtr).ManagedObject;
internal static T FindDelegate<T>(IntPtr thisPtr)
where T : class, System.Delegate => (T)(UnmanagedObject.FindObject<Delegate>(thisPtr).Target);
public static IUnknownVftbl IUnknownVftbl { get; } = new IUnknownVftbl
{
QueryInterface = Do_Abi_QueryInterface,
AddRef = Do_Abi_AddRef,
Release = Do_Abi_Release
};
private static int Do_Abi_QueryInterface(IntPtr pThis, ref Guid iid, out IntPtr ptr)
{
return UnmanagedObject.FindObject<ComCallableWrapper>(pThis).QueryInterface(iid, out ptr);
}
private static uint Do_Abi_AddRef(IntPtr pThis)
{
return UnmanagedObject.FindObject<ComCallableWrapper>(pThis).AddRef();
}
private static uint Do_Abi_Release(IntPtr pThis)
{
return UnmanagedObject.FindObject<ComCallableWrapper>(pThis).Release();
}
private class RuntimeWrapperCleanup
{
public IntPtr _identityComObject;
public WeakReference<object> _runtimeWrapper;
public RuntimeWrapperCleanup(IntPtr identityComObject, WeakReference<object> runtimeWrapper)
{
_identityComObject = identityComObject;
_runtimeWrapper = runtimeWrapper;
}
~RuntimeWrapperCleanup()
{
// If runtimeWrapper is still alive, then we need to go back into the finalization queue
// so we can check again later.
if (_runtimeWrapper.TryGetTarget(out var _))
{
GC.ReRegisterForFinalize(this);
}
else
{
((ICollection<KeyValuePair<IntPtr, WeakReference<object>>>)RuntimeWrapperCache).Remove(new KeyValuePair<IntPtr, WeakReference<object>>(_identityComObject, _runtimeWrapper));
}
}
}
}
struct ComInterfaceEntry
{
public IntPtr Vtable;
public Guid IID;
}
struct UnmanagedObject
{
public IntPtr _vftblPtr;
public IntPtr _gchandlePtr;
internal static T FindObject<T>(IntPtr thisPtr)
{
UnmanagedObject unmanagedObject = Marshal.PtrToStructure<UnmanagedObject>(thisPtr);
GCHandle thisHandle = GCHandle.FromIntPtr(unmanagedObject._gchandlePtr);
return (T)thisHandle.Target;
}
}
internal class RefCountingWrapperBase
{
private volatile IntPtr _strongHandle;
protected GCHandle WeakHandle { get; }
private int _refs = 0;
public RefCountingWrapperBase()
{
_strongHandle = IntPtr.Zero;
WeakHandle = GCHandle.Alloc(this, GCHandleType.WeakTrackResurrection);
}
~RefCountingWrapperBase()
{
WeakHandle.Free();
}
internal uint AddRef()
{
uint refs = (uint)System.Threading.Interlocked.Increment(ref _refs);
// We now own a reference. Let's try to create a strong handle if we don't already have one.
if (refs == 1)
{
GCHandle strongHandle = GCHandle.Alloc(this);
IntPtr previousStrongHandle = Interlocked.Exchange(ref _strongHandle, GCHandle.ToIntPtr(strongHandle));
if (previousStrongHandle != IntPtr.Zero)
{
// We've set a new handle. Release the old strong handle if there was one.
GCHandle.FromIntPtr(previousStrongHandle).Free();
}
}
return refs;
}
internal uint Release()
{
if (_refs == 0)
{
throw new InvalidOperationException("WinRT wrapper has been over-released!");
}
IntPtr currentStrongHandle = _strongHandle;
var refs = (uint)System.Threading.Interlocked.Decrement(ref _refs);
if (refs == 0)
{
// No more references. We need to remove the strong reference to make sure we don't stay alive forever.
// Only remove the strong handle if someone else doesn't change the strong handle
// If the strong handle changes, then someone else released and re-acquired the strong handle, meaning someone is holding a reference
IntPtr oldStrongHandle = Interlocked.CompareExchange(ref _strongHandle, IntPtr.Zero, currentStrongHandle);
// If _refs != 0, then someone AddRef'd this back from zero
// so we can't release this handle.
if (oldStrongHandle == currentStrongHandle)
{
GCHandle.FromIntPtr(currentStrongHandle).Free();
}
}
return refs;
}
}
internal class ComCallableWrapper : RefCountingWrapperBase
{
private Dictionary<Guid, IntPtr> _managedQITable;
public object ManagedObject { get; }
public ComWrappersSupport.InspectableInfo InspectableInfo { get; }
public IntPtr IdentityPtr { get; }
internal ComCallableWrapper(object obj)
{
ManagedObject = obj;
var (inspectableInfo, interfaceTableEntries) = ComWrappersSupport.PregenerateNativeTypeInformation(ManagedObject);
InspectableInfo = inspectableInfo;
interfaceTableEntries.Add(new ComInterfaceEntry
{
IID = typeof(IUnknownVftbl).GUID,
Vtable = IUnknownVftbl.AbiToProjectionVftblPtr
});
interfaceTableEntries.Add(new ComInterfaceEntry
{
IID = typeof(IInspectable).GUID,
Vtable = IInspectable.Vftbl.AbiToProjectionVftablePtr
});
InitializeManagedQITable(interfaceTableEntries);
IdentityPtr = _managedQITable[typeof(IUnknownVftbl).GUID];
}
~ComCallableWrapper()
{
foreach (var obj in _managedQITable.Values)
{
Marshal.FreeCoTaskMem(obj);
}
_managedQITable.Clear();
}
private void InitializeManagedQITable(List<ComInterfaceEntry> entries)
{
_managedQITable = new Dictionary<Guid, IntPtr>();
foreach (var entry in entries)
{
unsafe
{
UnmanagedObject* ifaceTearOff = (UnmanagedObject*)Marshal.AllocCoTaskMem(sizeof(UnmanagedObject));
ifaceTearOff->_vftblPtr = entry.Vtable;
ifaceTearOff->_gchandlePtr = GCHandle.ToIntPtr(WeakHandle);
_managedQITable.Add(entry.IID, (IntPtr)ifaceTearOff);
}
}
}
internal int QueryInterface(Guid iid, out IntPtr ptr)
{
const int E_NOINTERFACE = unchecked((int)0x80004002);
if (_managedQITable.TryGetValue(iid, out ptr))
{
AddRef();
return 0;
}
return E_NOINTERFACE;
}
}
partial class Delegate : RefCountingWrapperBase
{
private static Delegate FindObject(IntPtr thisPtr) => UnmanagedObject.FindObject<Delegate>(thisPtr);
// IUnknown
static unsafe readonly IUnknownVftbl._QueryInterface _QueryInterface = new IUnknownVftbl._QueryInterface(QueryInterface);
static readonly IUnknownVftbl._AddRef _AddRef = new IUnknownVftbl._AddRef(AddRef);
static readonly IUnknownVftbl._Release _Release = new IUnknownVftbl._Release(Release);
static unsafe int QueryInterface([In] IntPtr thisPtr, [In] ref Guid iid, [Out] out IntPtr obj)
{
const int E_NOINTERFACE = unchecked((int)0x80004002);
if (iid == typeof(IUnknownVftbl).GUID)
{
AddRef(thisPtr);
obj = thisPtr;
return 0; // S_OK;
}
obj = IntPtr.Zero;
return E_NOINTERFACE;
}
static uint AddRef([In] IntPtr thisPtr)
{
return FindObject(thisPtr).AddRef();
}
static uint Release([In] IntPtr thisPtr)
{
return FindObject(thisPtr).Release();
}
static IDelegateVftbl _vftblTemplate;
static Delegate()
{
// lay out the vftable
_vftblTemplate.QueryInterface = Marshal.GetFunctionPointerForDelegate(_QueryInterface);
_vftblTemplate.AddRef = Marshal.GetFunctionPointerForDelegate(_AddRef);
_vftblTemplate.Release = Marshal.GetFunctionPointerForDelegate(_Release);
_vftblTemplate.Invoke = IntPtr.Zero;
}
readonly UnmanagedObject _unmanagedObj;
public readonly IntPtr ThisPtr;
private global::System.Delegate _abiInvoke;
public global::System.Delegate Target { get; }
public Delegate(global::System.Delegate abiInvoke, global::System.Delegate managedDelegate)
{
_abiInvoke = abiInvoke;
var vftbl = _vftblTemplate;
vftbl.Invoke = Marshal.GetFunctionPointerForDelegate(abiInvoke);
_unmanagedObj._vftblPtr = Marshal.AllocCoTaskMem(Marshal.SizeOf(_vftblTemplate));
Marshal.StructureToPtr(vftbl, _unmanagedObj._vftblPtr, false);
Target = managedDelegate;
_unmanagedObj._gchandlePtr = GCHandle.ToIntPtr(WeakHandle);
ThisPtr = Marshal.AllocCoTaskMem(Marshal.SizeOf(_unmanagedObj));
Marshal.StructureToPtr(_unmanagedObj, ThisPtr, false);
}
~Delegate()
{
Marshal.FreeCoTaskMem(ThisPtr);
}
}
#endif
}