Vì vậy, nếu tôi muốn thông qua một danh sách đến hàm callback của tôi thông qua WINAPI tôi sử dụng 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 để David Heffernan
Edit: Như đã đề cập trong các ý kiến, bạn cần phải giải phóng tay cầm sau khi sử dụng. Ngoài ra tôi đã sử dụng đúc. Có thể sử dụng các phương pháp đo lường tĩnh là GCHandle.ToIntPtr(handle1)
và GCHandle.FromIntPtr(parameter)
như here. Tôi chưa kiểm tra điều đó.
Ghim nó bằng GCHandle –