I am trying to write C # P / Invoke for the C API (native Win dll) and it usually works fine. The only exception is the specific method that takes the structure as a parameter in the C code. The function is called without any exceptions, but returns false, indicating that something failed to execute.
In the API header file, the involved method and structures are defined as follows:
#define MAX_ICE_MS_TRACK_LENGTH 256 typedef struct tagTRACKDATA { UINT nLength; BYTE TrackData[MAX_ICE_MS_TRACK_LENGTH]; } TRACKDATA, FAR* LPTRACKDATA; typedef const LPTRACKDATA LPCTRACKDATA; BOOL ICEAPI EncodeMagstripe(HDC , LPCTRACKDATA , LPCTRACKDATA , LPCTRACKDATA , LPCTRACKDATA );
I tried to create a C # P / Invoke shell using the following code:
public const int MAX_ICE_MS_TRACK_LENGTH = 256; [StructLayout(LayoutKind.Sequential)] public class MSTrackData { public UInt32 nLength; public readonly Byte[] TrackData = new byte[MAX_ICE_MS_TRACK_LENGTH]; } [DllImport("ICE_API.dll", CharSet = CharSet.Auto, SetLastError = true)] public static extern bool EncodeMagstripe(IntPtr hDC, [In]ref MSTrackData pTrack1, [In]ref MSTrackData pTrack2, [In]ref MSTrackData pTrack3, [In]ref MSTrackData reserved);
Then I try to call the EncodeMagstripe method using the following C # code:
CardApi.MSTrackData trackNull = null; CardApi.MSTrackData track2 = new CardApi.TrackData(); byte[] trackBytes = Encoding.ASCII.GetBytes(";0123456789?"); track2.nLength = (uint)trackBytes.Length; Buffer.BlockCopy(trackBytes, 0, track2.TrackData, 0, trackBytes.Length); if (!CardApi.EncodeMagstripe(hDC, ref trackNull, ref track2, ref trackNull, ref trackNull)) { throw new ApplicationException("EncodeMagstripe failed", Marshal.GetLastWin32Error()); }
This throws an ApplicationException, and the error code is 801, which according to the documentation means that "The data contains too many characters for the selected track format 2". However, the selected track format should contain up to 39 characters (I also tried shorter lines).
I suspect that the problem is due to the fact that I was mistaken in defining MSTrackData, but I do not see what it could be. Anyone have any suggestions?