I need to use an external DLL to send data to the device. The method that I use in the DLL takes a pointer to an array of bytes as a parameter. Since I use C #, I use the GCHandle.Alloc method to get the memory address and assign it to an IntPtr instance. Then I pass IntPtr as a parameter. My concern is that there may be a risk of memory leak in the code, since I had not used pointers and memory allocation in C # before. The code currently works as shown:
GCHandle pinned = GCHandle.Alloc(byteArray, GCHAndleType.Pinned); IntPtr arrayPtr = pinned.AddrOfPinnedObject(); var result = _externalDll.SendInfo(arrayPtr, byteArray.Length); pinned.Free();
Is this the correct way to assign and use IntPtr? This seems to work, but since it will be run approximately 100 times every day on a production machine, I would prefer to avoid any major issues.
source share