Skip to content

Commit

Permalink
fix(#8): Replace GCHandle by IntPtr.
Browse files Browse the repository at this point in the history
  • Loading branch information
vojtech committed Feb 9, 2025
1 parent cd40e6a commit c1596f2
Showing 1 changed file with 10 additions and 12 deletions.
22 changes: 10 additions & 12 deletions ScpiNet/UsbScpiConnection.cs
Original file line number Diff line number Diff line change
Expand Up @@ -702,14 +702,13 @@ private byte[] CreateTmcRequest(UsbTmcMsgId msgId, bool eom, byte[] data, uint l
byte[] buffer = new byte[bufferLength];

// Copy the header to the beginning of the array:
GCHandle handle = default;
IntPtr headerPtr = IntPtr.Zero;
try {
handle = GCHandle.Alloc(buffer, GCHandleType.Pinned);
Marshal.StructureToPtr<UsbTmcHeader>(header, handle.AddrOfPinnedObject(), false);
headerPtr = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(UsbTmcHeader)));
Marshal.StructureToPtr(header, headerPtr, true);
Marshal.Copy(headerPtr, buffer, 0, Marshal.SizeOf(typeof(UsbTmcHeader)));
} finally {
if (handle.IsAllocated) {
handle.Free();
}
Marshal.FreeHGlobal(headerPtr);
}

// Add the write data after the header:
Expand Down Expand Up @@ -787,14 +786,13 @@ public async Task<ReadResult> Read(byte[] buffer, int readLength = -1, int speci
}

// Now convert data to the UsbTmcHeader structure:
GCHandle handle = default;
IntPtr headerPtr = IntPtr.Zero;
try {
handle = GCHandle.Alloc(receptionBuffer, GCHandleType.Pinned);
header = (UsbTmcHeader)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(UsbTmcHeader));
headerPtr = Marshal.AllocHGlobal(headerSize);
Marshal.Copy(receptionBuffer, 0, headerPtr, headerSize);
header = Marshal.PtrToStructure<UsbTmcHeader>(headerPtr);
} finally {
if (handle.IsAllocated) {
handle.Free();
}
Marshal.FreeHGlobal(headerPtr);
}

// Unfortunately Keysight multimeter leaves Tag fields always zero in the response, therefore this check cannot be used:
Expand Down

0 comments on commit c1596f2

Please sign in to comment.