Bonnotbh
Bonnotbh

Reputation: 545

Possibility of memory leak risk - getting IntPtr from byte array in c#

I am having to use an external DLL to send data to a device. The method I'm using in the DLL takes a pointer to a byte array as a parameter. As I'm using C# I am using the GCHandle.Alloc method to get the memory address and assign it to an IntPtr instance. I then am passing the IntPtr as the parameter. My worry is that there could possibly be a memory leak risk in the code, as I have 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 the IntPtr? It seems to work but as this is going to be run about 100 times concurrently each day on a production machine I'd rather avoid any major problems.

Upvotes: 4

Views: 1070

Answers (1)

Stephen Martin
Stephen Martin

Reputation: 9645

In general, the only time you need to use a GCHandle is when the unmanaged code will be keeping a reference to your pointer for later use.

Here you just seem to be passing in the pointer and then immediately freeing it. If this is the case then you shouldn't be using a GCHandle at all. Just make your first parameter a byte[] and pass the byteArray directly. The runtime will take care of pinning the array object for the duration of the call and will pass a pointer to the first element of the array to the unmanaged code.

Upvotes: 3

Related Questions