Więc jeśli chcę przekazać listę do mojej funkcji wywołania zwrotnego poprzez WinAPI używam GCHandle
// object to IntPtr (before calling WinApi):
List<string> list1 = new List<string>();
GCHandle handle1 = GCHandle.Alloc(list1);
IntPtr parameter = (IntPtr) handle1;
// call WinAPi and pass the parameter here
// then free the handle when not needed:
handle1.Free();
// back to object (in callback function):
GCHandle handle2 = (GCHandle) parameter;
List<string> list2 = (handle2.Target as List<string>);
list2.Add("hello world");
Thx do David Heffernan
EDIT: Jak zauważył w komentarzach, trzeba uwolnić uchwyt po użyciu. Również używałem odlewania. Rozsądne może być użycie statycznego metgods GCHandle.ToIntPtr(handle1)
i GCHandle.FromIntPtr(parameter)
, takich jak here. Nie sprawdziłem tego.
Przypnij za pomocą GCHandle –