2
votes

I'm creating a .NET Windows service to communicate with a smart card reader. The maincomponent is a Windows DLL called winscard.dll which I'm using with DLLImport attribute in the .NET code. Everything works fine on Windows XP 32 bit, but when i running it on Windows 7 x64 i recive 0x6 ERROR_INVALID_HANDLE result when calling SCardTransmit. The application (the service as command line app) can connect to the card reader but cannot read anything from the card.

Any idea?

1
Have you tried build your .NET application as a 32 BIT program rather than anycpu?Mike Miller
If i build it as 32 bit app, then: Unhandled Exception: System.AccessViolationException: Attempted to read or write protected memory. This is often an indication that other memory is corrupt. at Microsoft.Win32.Win32Native.CoTaskMemFree(IntPtr ptr) at SmartCard.SmartCardBase.SCardListReaderGroups(Int32 hContext, String& cGro ups, Int32& nStringSize) at SmartCard.SmartCardBase.InitializeCardReader() in C:\Data\K7 Intranet\Smar tCard\SmartCardBase.cs:line 152 at SmartCard.Program.Main(String[] args) in C:\Data\K7 Intranet\SmartCard\Pro gram.cs:line 14Peter Kiss
It seems you aren't the only one (groupsrv.com/dotnet/about280604.html). It doesn't much more information then you already have though.Mike Miller
The solution: use IntPtr instead of int (any type) and implement all winscard.dll method good, help: pinvoke.netPeter Kiss

1 Answers

4
votes

You have problems with SCardEstablishContext it will return 0 but handle also 0. Use IntPtr instead of Integer:

Public Declare Function SCardEstablishContext Lib "Winscard.dll" (ByVal dwScope As Integer, _
                                                                      ByVal pvReserved1 As Integer, _
                                                                      ByVal pvReserved2 As Integer, _
                                                                      ByRef phContext As IntPtr) As Integer

phContext will be store valid value in Windows x64 (Windows 8 x64 and Windows 2008 via RDP tested). Also replace other "Integer" to "IntPtr" when it used as handle.

Public Declare Function SCardConnect Lib "Winscard.dll" Alias "SCardConnectA" (ByVal hContext As IntPtr, _
                                                                                   ByVal szReaderName As String, _
                                                                                   ByVal dwShareMode As Integer, _
                                                                                   ByVal dwPrefProtocol As Integer, _
                                                                                   ByRef hCard As IntPtr, _
                                                                                   ByRef ActiveProtocol As IntPtr) As Integer