Search code examples
javascriptwindowssmartcardjsctypes

js-ctypes invalid arguments


Iam trying to run winscard functions using js-ctypes in Firefox. I have working C code and I started to copy code to javascipt. Unfortunetly my first function- SCardEstablishContext returns the following error:

SCARD_E_INVALID_PARAMETER 0x80100004

Whats wrong with the arguments?

Components.utils.import("resource://gre/modules/ctypes.jsm");
const NULL = ctypes.voidptr_t(0);

var cardLib = ctypes.open("C:\\WINDOWS\\system32\\WinSCard.dll");
var SCardEstablishContext = cardLib.declare("SCardEstablishContext", ctypes.winapi_abi, ctypes.uint32_t, ctypes.uint32_t, ctypes.voidptr_t, ctypes.voidptr_t, ctypes.voidptr_t);
var ContextHandle = new ctypes.voidptr_t();
var ret = SCardEstablishContext(2, NULL, NULL, ContextHandle);
cardLib.close();

Solution

  • The last parameter of SCardEstablishContext (phContext) should be a pointer to a 32-bit integer. Upon success, SCardEstablishContext populates this integer value with the handle to the SCARD context.

    You define ContextHandle as new uninitialized instance of ctypes.voidptr_t, which is essentially the same as ctypes.voidptr_t(0) (hence, a null-pointer). You then pass this null-pointer to SCardEstablishContext, which, conequently, cannot assign a value (as the reference/pointer is not backed by actual data memory).

    Thus, you should define ContextHandle as a voidptr_t (32-bit integer on 32-bit platforms / 64-bit integer on 64-bit platforms)

    var ContextHandle = ctypes.voidptr_t(0);
    

    and then pass the pointer to this ContextHandle to the SCardEstablishContext function:

    var ret = SCardEstablishContext(2, NULL, NULL, ContextHandle.address());