SCard Rust Reference Documentation

SCard

Current Version: 11.6.1

Chilkat.SCard

Communicate directly with smart card readers and cards through PC/SC.

Chilkat.SCard is the low-level PC/SC smart card interface for applications that need direct reader and card communication. It supports reader discovery, reader connection, card status checking, APDU transmission, reader-control commands, status-change monitoring, transactions, and diagnostic access to underlying PC/SC errors. Use this class when the application needs APDU-level control rather than a higher-level certificate, minidriver, or PKCS#11 abstraction.

Reader discovery

Enumerate available PC/SC smart card readers and identify the reader the application should use.

Connect to cards

Connect to a reader/card, check card presence and status, and manage the active PC/SC connection.

Transmit APDUs

Send APDU commands directly to the card and receive the raw response bytes and status words.

Reader-control commands

Issue lower-level reader control commands when supported by the reader driver and PC/SC environment.

Status monitoring

Monitor reader or card status changes so applications can detect card insertion, removal, or state changes.

Transactions and diagnostics

Use PC/SC transactions for coordinated card access and inspect detailed error information when reader or card operations fail.

Common pattern: Establish the PC/SC context, list readers, connect to the selected reader, check card status, transmit APDU commands, process the response bytes, and disconnect when finished. Use Chilkat.SCard for direct PC/SC reader and APDU-level work; use Chilkat.ScMinidriver for card-minidriver certificate and key-container operations, and Chilkat.Pkcs11 for PKCS#11 token or HSM sessions.

Object Creation

// Cargo.toml:
//     [dependencies]
//     chilkat = "11.6"

use chilkat::SCard;

// Once per process, before any other Chilkat call:
chilkat::unlock_bundle("Anything for 30-day trial")?;  // shorthand for Global::new().unlock_bundle(..)

let s_card = SCard::new();
// ... the native object is freed when `s_card` goes out of scope.
pub fn new() -> SCard

Creates the underlying native Chilkat object (SCard also implements Default). Every method takes &self, so the object never needs to be declared mut. A SCard is Send but not Sync: it may be moved to another thread, but a reference to it cannot be shared between threads at the same time.

impl Drop for SCard

The native object is freed when the SCard is dropped — when it goes out of scope, or explicitly with drop(s_card). There is no Dispose method to call.

Errors

Methods that can fail return chilkat::Result<T>, which is Result<T, chilkat::Error>: a method whose only outcome is success or failure returns Result<()>, a method producing a string or an object returns Result<String> or Result<SCard>. The error carries the object's LastErrorText at the time of the failure (Error::last_error_text), the class and method names, and implements std::error::Error, so ? works in any function returning chilkat::Result or a Box<dyn Error>. Properties never fail, and methods that answer a question (has_..., is_..., ...) return a plain bool.

match s_card.some_method(...) {
    Ok(value) => println!("{value:?}"),
    Err(e) => eprintln!("{}", e.last_error_text()),
}

Properties

ActiveProtocol
// read-only
pub fn active_protocol(&self) -> String
Introduced in version 9.50.87

The name of the active protocol if connected smart card reader, or an empty string if not connected. Possible values are T0, T1, raw, undefined, or if not connected to a reader.

top
CardAtr
// read-only
pub fn card_atr(&self) -> String
Introduced in version 9.50.87

This is the Current ATR of a card in the connected reader.

top
ConnectedReader
// read-only
pub fn connected_reader(&self) -> String
Introduced in version 9.50.87

The name of the currently connected smart card reader, or an empty string if not connected.

top
Context
// read-only
pub fn context(&self) -> String
Introduced in version 9.50.87

Contains the string user or system if this object has established a context (by calling EstablishContext). Contains the empty string if no context is established.

top
DebugLogFilePath
// read/write
pub fn debug_log_file_path(&self) -> String
pub fn set_debug_log_file_path(&self, value: &str)

If set to a file path, this property logs the LastErrorText of each Chilkat method or property call to the specified file. This logging helps identify the context and history of Chilkat calls leading up to any crash or hang, aiding in debugging.

Enabling the VerboseLogging property provides more detailed information. This property is mainly used for debugging rare instances where a Chilkat method call causes a hang or crash, which should generally not happen.

Possible causes of hangs include:

  • A timeout property set to 0, indicating an infinite timeout.
  • A hang occurring within an event callback in the application code.
  • An internal bug in the Chilkat code causing the hang.

More Information and Examples
top
LastErrorHtml
// read-only
pub fn last_error_html(&self) -> String

Provides HTML-formatted information about the last called method or property. If a method call fails or behaves unexpectedly, check this property for details. Note that information is available regardless of the method call's success.

top
LastErrorText
// read-only
pub fn last_error_text(&self) -> String

Provides plain text information about the last called method or property. If a method call fails or behaves unexpectedly, check this property for details. Note that information is available regardless of the method call's success.

top
LastErrorXml
// read-only
pub fn last_error_xml(&self) -> String

Provides XML-formatted information about the last called method or property. If a method call fails or behaves unexpectedly, check this property for details. Note that information is available regardless of the method call's success.

top
LastMethodSuccess
// read/write
pub fn last_method_success(&self) -> bool
pub fn set_last_method_success(&self, value: bool)

Indicates the success or failure of the most recent method call: true means success, false means failure. This property remains unchanged by property setters or getters. This method is present to address challenges in checking for null or Nothing returns in certain programming languages. Note: This property does not apply to methods that return integer values or to boolean-returning methods where the boolean does not indicate success or failure.

top
PcscLibPath
// read/write
pub fn pcsc_lib_path(&self) -> String
pub fn set_pcsc_lib_path(&self, value: &str)
Introduced in version 9.50.87

For Linux systems only. Specifies the full path of the libpcsclite.so shared lib. This property should only be used if the libpcsclite.so is in a non-standard location or if Chilkat cannot automatically located it.

top
ReaderStatus
// read-only
pub fn reader_status(&self) -> String
Introduced in version 9.50.87

The current status of the connected reader. Possible values are:

  • absent - There is no card in the reader.
  • present - There is a card in the reader, but it has not been moved into position for use.
  • swallowed - There is a card in the reader in position for use. The card is not powered.
  • powered - Power is being provided to the card, but the reader driver is unaware of the mode of the card.
  • negotiable - The card has been reset and is awaiting PTS negotiation.
  • specific - The card has been reset and specific communication protocols have been established.

top
ScardError
// read-only
pub fn scard_error(&self) -> String
Introduced in version 9.50.87

The last error returned by an underlying PC/SC function. Can be one of the following:

  • SCARD_W_REMOVED_CARD - The smart card has been removed, so that further communication is not possible.
  • SCARD_W_RESET_CARD - The smart card has been reset, so any shared state information is invalid.
  • ...

top
VerboseLogging
// read/write
pub fn verbose_logging(&self) -> bool
pub fn set_verbose_logging(&self, value: bool)

If set to true, then the contents of LastErrorText (or LastErrorXml, or LastErrorHtml) may contain more verbose information. The default value is false. Verbose logging should only be used for debugging. The potentially large quantity of logged information may adversely affect peformance.

top
Version
// read-only
pub fn version(&self) -> String

Version of the component/library, such as "10.1.0"

More Information and Examples
top

Methods

BeginTransaction
pub fn begin_transaction(&self) -> Result<()>
Introduced in version 9.50.87

Establishes a temporary exclusive access mode for doing a series of commands in a transaction.

Returns Ok(()) for success, Err(chilkat::Error) for failure.

top
CheckStatus
pub fn check_status(&self) -> Result<()>
Introduced in version 9.50.87

Check the current status of the currently connected reader. Calling this method updates the ReaderStatus, ActiveProtocol, and CardAtr properties. If this method returns false, none of the properties are updated.

Returns Ok(()) for success, Err(chilkat::Error) for failure.

top
Connect
pub fn connect(&self, reader: &str, share_mode: &str, preferred_protocol: &str) -> Result<()>
Introduced in version 9.50.87

Establish a connection to a reader. The reader is the name of a reader returned from ListReaders. The share_mode can be shared, exclusive, or direct. The preferred_protocol can be 0 (valid only if the shareMode = direct), T0, T1, raw, or no_preference. (No preference is effectively T0 or T1.)

If successful, the state of this object instance is that it's connected to the reader.

Returns Ok(()) for success, Err(chilkat::Error) for failure.

top
Disconnect
pub fn disconnect(&self, disposition: &str) -> Result<()>
Introduced in version 9.50.87

Terminates a connection with a reader. The disposition can be one of the following values:

  • leave: Do nothing.
  • reset: Reset the card (warm reset).
  • unpower: Power down the card (cold reset).
  • eject: Eject the card.

Returns Ok(()) for success, Err(chilkat::Error) for failure.

top
EndTransaction
pub fn end_transaction(&self, disposition: &str) -> Result<()>
Introduced in version 9.50.87

Ends a previously begun transaction. The disposition is the action to be taken on the reader, and can be leave which is to do nothing, reset, unpower, or eject.

Returns Ok(()) for success, Err(chilkat::Error) for failure.

top
EstablishContext
pub fn establish_context(&self, scope: &str) -> Result<()>
Introduced in version 9.5.0.87

Creates an Application Context to the PC/SC Resource Manager. This must be the first WinSCard function called in a PC/SC application. The scope can be user or system. After calling, this object will have context and all other methods will use the established context. The Context property will hold the value user or system if context was established, or will be empty if no context was established.

Returns Ok(()) for success, Err(chilkat::Error) for failure.

top
FindSmartcards
pub fn find_smartcards(&self, json: &JsonObject) -> Result<()>
Introduced in version 9.50.87

Returns JSON containing information about the smartcards currently inserted into readers.

Returns Ok(()) for success, Err(chilkat::Error) for failure.

More Information and Examples
top
GetAttrib
pub fn get_attrib(&self, attr: &str, bd: &BinData) -> Result<()>
Introduced in version 9.50.87

Get an attribute from the IFD Handler (reader driver).

The attr can be one of the following:

  • ASYNC_PROTOCOL_TYPES
  • ATR_STRING
  • CHANNEL_ID
  • CHARACTERISTICS
  • CURRENT_BWT
  • CURRENT_CLK
  • CURRENT_CWT
  • CURRENT_D
  • CURRENT_EBC_ENCODING
  • CURRENT_F
  • CURRENT_IFSC
  • CURRENT_IFSD
  • CURRENT_IO_STATE
  • CURRENT_N
  • CURRENT_PROTOCOL_TYPE
  • CURRENT_W
  • DEFAULT_CLK
  • DEFAULT_DATA_RATE
  • DEVICE_FRIENDLY_NAME
  • DEVICE_IN_USE
  • DEVICE_SYSTEM_NAME
  • DEVICE_UNIT
  • ESC_AUTHREQUEST
  • ESC_CANCEL
  • ESC_RESET
  • EXTENDED_BWT
  • ICC_INTERFACE_STATUS
  • ICC_PRESENCE
  • ICC_TYPE_PER_ATR
  • MAX_CLK
  • MAX_DATA_RATE
  • MAX_IFSD
  • MAXINPUT
  • POWER_MGMT_SUPPORT
  • SUPRESS_T1_IFS_REQUEST
  • SYNC_PROTOCOL_TYPES
  • USER_AUTH_INPUT_DEVICE
  • USER_TO_CARD_AUTH_DEVICE
  • VENDOR_IFD_SERIAL_NO
  • VENDOR_IFD_TYPE
  • VENDOR_IFD_VERSION
  • VENDOR_NAME

The attribute data is returned in bd.

Returns Ok(()) for success, Err(chilkat::Error) for failure.

top
GetAttribStr
pub fn get_attrib_str(&self, attr: &str) -> Result<String>
Introduced in version 9.50.87

Get a string typed attribute from the IFD Handler (reader driver).

The attr can be one of the following, but should be limited to the particular attributes that return string values.

  • ASYNC_PROTOCOL_TYPES
  • ATR_STRING
  • CHANNEL_ID
  • CHARACTERISTICS
  • CURRENT_BWT
  • CURRENT_CLK
  • CURRENT_CWT
  • CURRENT_D
  • CURRENT_EBC_ENCODING
  • CURRENT_F
  • CURRENT_IFSC
  • CURRENT_IFSD
  • CURRENT_IO_STATE
  • CURRENT_N
  • CURRENT_PROTOCOL_TYPE
  • CURRENT_W
  • DEFAULT_CLK
  • DEFAULT_DATA_RATE
  • DEVICE_FRIENDLY_NAME
  • DEVICE_IN_USE
  • DEVICE_SYSTEM_NAME
  • DEVICE_UNIT
  • ESC_AUTHREQUEST
  • ESC_CANCEL
  • ESC_RESET
  • EXTENDED_BWT
  • ICC_INTERFACE_STATUS
  • ICC_PRESENCE
  • ICC_TYPE_PER_ATR
  • MAX_CLK
  • MAX_DATA_RATE
  • MAX_IFSD
  • MAXINPUT
  • POWER_MGMT_SUPPORT
  • SUPRESS_T1_IFS_REQUEST
  • SYNC_PROTOCOL_TYPES
  • USER_AUTH_INPUT_DEVICE
  • USER_TO_CARD_AUTH_DEVICE
  • VENDOR_IFD_SERIAL_NO
  • VENDOR_IFD_TYPE
  • VENDOR_IFD_VERSION
  • VENDOR_NAME

Returns Err(chilkat::Error) on failure.

top
GetAttribUint
pub fn get_attrib_uint(&self, attr: &str) -> u32
Introduced in version 9.50.87

Get an unsigned integer typed attribute from the IFD Handler (reader driver).

The attr can be one of the following, but should be limited to the particular attributes that return unsigned integer values.

  • ASYNC_PROTOCOL_TYPES
  • ATR_STRING
  • CHANNEL_ID
  • CHARACTERISTICS
  • CURRENT_BWT
  • CURRENT_CLK
  • CURRENT_CWT
  • CURRENT_D
  • CURRENT_EBC_ENCODING
  • CURRENT_F
  • CURRENT_IFSC
  • CURRENT_IFSD
  • CURRENT_IO_STATE
  • CURRENT_N
  • CURRENT_PROTOCOL_TYPE
  • CURRENT_W
  • DEFAULT_CLK
  • DEFAULT_DATA_RATE
  • DEVICE_FRIENDLY_NAME
  • DEVICE_IN_USE
  • DEVICE_SYSTEM_NAME
  • DEVICE_UNIT
  • ESC_AUTHREQUEST
  • ESC_CANCEL
  • ESC_RESET
  • EXTENDED_BWT
  • ICC_INTERFACE_STATUS
  • ICC_PRESENCE
  • ICC_TYPE_PER_ATR
  • MAX_CLK
  • MAX_DATA_RATE
  • MAX_IFSD
  • MAXINPUT
  • POWER_MGMT_SUPPORT
  • SUPRESS_T1_IFS_REQUEST
  • SYNC_PROTOCOL_TYPES
  • USER_AUTH_INPUT_DEVICE
  • USER_TO_CARD_AUTH_DEVICE
  • VENDOR_IFD_SERIAL_NO
  • VENDOR_IFD_TYPE
  • VENDOR_IFD_VERSION
  • VENDOR_NAME

Returns 0xFFFFFFFF on failure.

top
GetStatusChange
pub fn get_status_change(&self, max_wait_ms: i32, st_reader_names: &StringTable, json: &JsonObject) -> Result<()>
Introduced in version 9.50.87

Blocks execution until the current availability of the cards in a specific set of readers changes.

This function receives a list of reader names in st_reader_names. It then blocks waiting for a change in state to occur for a maximum blocking time of max_wait_ms (in milliseconds) or forever if 0 is used.

Information about the current reader states and which reader(s) changed is returned in json. See the example below for more information.

To wait for a reader event (reader added or removed) you may use the special reader name \\?PnP?\Notification.

To cancel the ongoing call, call Cancel().

The st_reader_names contains the reader names to check. The json is empty on input, and if the call returns success contains information about the state (after the event change) of each reader.

Returns Ok(()) for success, Err(chilkat::Error) for failure.

top
GetStatusChangeCancel
pub fn get_status_change_cancel(&self) -> Result<()>
Introduced in version 9.50.87

Cancels an ongoing GetStatusChange method call. This would be called from a separate thread in your application if GetStatusChange was called synchronously.

Returns Ok(()) for success, Err(chilkat::Error) for failure.

top
ListReaderGroups
pub fn list_reader_groups(&self, reader_groups: &StringTable) -> Result<()>
Introduced in version 9.50.87

Returns a list of currently available reader groups on the system. The reader groups are returned in reader_groups.

Returns Ok(()) for success, Err(chilkat::Error) for failure.

top
ListReaders
pub fn list_readers(&self, st: &StringTable) -> Result<()>
Introduced in version 9.50.87

Returns a list of currently available readers on the system.

Returns Ok(()) for success, Err(chilkat::Error) for failure.

More Information and Examples
top
Reconnect
pub fn reconnect(&self, share_mode: &str, preferred_protocol: &str, action: &str) -> Result<()>
Introduced in version 9.50.87

Reestablishes a connection to a reader that was previously connected to using Connect().

In a multi application environment it is possible for an application to reset the card in shared mode. When this occurs any other application trying to access certain commands will be returned the value SCARD_W_RESET_CARD. When this occurs Reconnect() must be called in order to acknowledge that the card was reset and allow it to change its state accordingly.

The share_mode can be shared, exclusive, or direct. The preferred_protocol can be 0 (valid only if the shareMode = direct), T0, T1, raw, or no_preference. (No preference is effectively T0 or T1.) The action is the desired action taken on the card/reader. It can be leave, reset, unpower, or eject.

If successful, the state of this object instance is that it's connected to the reader.

Returns Ok(()) for success, Err(chilkat::Error) for failure.

top
ReleaseContext
pub fn release_context(&self) -> Result<()>
Introduced in version 9.50.87

Destroys a communication context to the PC/SC Resource Manager. This must be the last function called in a PC/SC application.

Returns Ok(()) for success, Err(chilkat::Error) for failure.

top
SendControl
pub fn send_control(&self, control_code: u32, bd_send: &BinData, bd_recv: &BinData) -> Result<()>
Introduced in version 9.50.87

Sends a command directly to the IFD Handler (reader driver) to be processed by the reader.

This is useful for creating client side reader drivers for functions like PIN pads, biometrics, or other extensions to the normal smart card reader that are not normally handled by PC/SC.

The command data is sent in bd_send. The response is written to bd_recv.

Returns Ok(()) for success, Err(chilkat::Error) for failure.

top
SendControlHex
pub fn send_control_hex(&self, control_code: u32, send_data: &str, bd_recv: &BinData) -> Result<()>
Introduced in version 9.50.87

Sends a command directly to the IFD Handler (reader driver) to be processed by the reader.

This is useful for creating client side reader drivers for functions like PIN pads, biometrics, or other extensions to the normal smart card reader that are not normally handled by PC/SC.

The command data is provided as a hex string in send_data. The response is written to bd_recv.

Returns Ok(()) for success, Err(chilkat::Error) for failure.

top
Transmit
pub fn transmit(&self, protocol_name: &str, bd_send: &BinData, bd_recv: &BinData, max_recv_len: i32) -> Result<()>
Introduced in version 9.50.87

Sends an APDU to the smart card contained in the currently connected reader. The protocol_name can be T0, T1, or raw. The APDU to be sent is contained in bd_send. The response from the card is contained in bd_recv. The max_recv_len is the maximum response size (in bytes) willing to be accepted.

Returns Ok(()) for success, Err(chilkat::Error) for failure.

top
TransmitHex
pub fn transmit_hex(&self, protocol_name: &str, apdu_hex: &str, bd_recv: &BinData, max_recv_len: i32) -> Result<()>
Introduced in version 9.50.87

Sends an APDU to the smart card contained in the currently connected reader. The protocol_name can be T0, T1, or raw. The APDU (in hexadecimal) to be sent is passed in apdu_hex. The response from the card is contained in bd_recv. The max_recv_len is the maximum response size (in bytes) willing to be accepted.

Returns Ok(()) for success, Err(chilkat::Error) for failure.

top

Events

All Chilkat methods are synchronous: the call returns when the work is done. During a call, SCard raises three events so your application can show progress and offer a way out. Implement the chilkat::EventHandler trait (every method has a do-nothing default, so implement only the events you need) and install it with set_event_handler:

use chilkat::{SCard, EventHandler};

struct Progress;

impl EventHandler for Progress {
    fn percent_done(&mut self, pct: i32) -> bool {
        println!("{pct}%");
        false   // return true to abort the method in progress
    }
    fn progress_info(&mut self, name: &str, value: &str) {
        println!("{name}: {value}");
    }
}

let s_card = SCard::new();
s_card.set_event_handler(Progress);
s_card.set_heartbeat_ms(250);   // raise abort_check 4 times per second during Chilkat calls

For a one-off handler the closure methods avoid writing a type; they may be combined, and each replaces the previously set closure for that one event (installing a closure removes a trait handler set earlier, and vice versa):

s_card.on_percent_done(|pct| { println!("{pct}%"); false });
s_card.on_progress_info(|name, value| println!("{name}: {value}"));
pub fn set_event_handler<H: EventHandler>(&self, handler: H)

Installs handler as the receiver of this object's events, replacing any handler or closures set earlier. The object owns the handler, which must be Send + 'static.

pub fn clear_event_handler(&self)

Removes the handler and any closures; events are no longer delivered.

AbortCheck fires at regular intervals controlled by the HeartbeatMs property (0, the default, disables it); PercentDone fires when an operation's completion percentage is known; ProgressInfo delivers named progress values. Returning true from abort_check or percent_done aborts the running method, which then returns Err.

Events fire on the thread that called the method, before that method returns. A panic inside a handler aborts the running method and is re-raised to the caller once the native library has returned, so it never unwinds through C frames. To abort a long operation from another thread, share an Arc<AtomicBool> with an abort_check handler, or set the object's AbortCurrent property to true.

AbortCheck
// EventHandler trait method; closure form: on_abort_check(FnMut() -> bool)
fn abort_check(&mut self) -> bool

Enables a method call to be aborted by triggering the AbortCheck event at intervals defined by the HeartbeatMs property. If HeartbeatMs is set to its default value of 0, no events will occur. For instance, set HeartbeatMs to 200 to trigger 5 AbortCheck events per second.

More Information and Examples

Example (closure form; the EventHandler trait method is equivalent):

s_card.set_heartbeat_ms(250);   // call abort_check 4 times per second

let stop = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
let flag = stop.clone();
s_card.on_abort_check(move || flag.load(std::sync::atomic::Ordering::Relaxed));
// ... another thread may now abort the method in progress with stop.store(true, Ordering::Relaxed)
top
PercentDone
// EventHandler trait method; closure form: on_percent_done(FnMut(i32) -> bool)
fn percent_done(&mut self, pct: i32) -> bool

This provides the percentage completion for any method involving network communications or time-consuming processing, assuming the progress can be measured as a percentage. This event is triggered only when it's possible and logical to express the operation's progress as a percentage. The pct_done argument will range from 1 to 100. For methods that finish quickly, the number of PercentDone callbacks may vary, but the final callback will have pct_done equal to 100. For longer operations, callbacks will not exceed one per percentage point (e.g., 1, 2, 3, ..., 98, 99, 100).

The PercentDone callback also acts as an AbortCheck event. For fast methods where PercentDone fires, an AbortCheck event may not trigger since the PercentDone callback already provides an opportunity to abort. For longer operations, where time between PercentDone callbacks is extended, AbortCheck callbacks enable more responsive operation termination.

To abort the operation, set the abort output argument to true. This will cause the method to terminate and return a failure status or corresponding failure value.

More Information and Examples

Example (closure form; the EventHandler trait method is equivalent):

s_card.on_percent_done(|pct| {
    // pct ranges from 1 to 100.
    println!("Percent done: {pct}");
    false   // return true to abort the method in progress
});
top
ProgressInfo
// EventHandler trait method; closure form: on_progress_info(FnMut(&str, &str))
fn progress_info(&mut self, name: &str, value: &str)

This event callback provides tag name/value pairs that detail what occurs during a method call. To discover existing tag names, create code to handle the event, emit the pairs, and review them. Most tag names are self-explanatory.

Note: Some Chilkat methods don't fire any ProgressInfo events.

More Information and Examples

Example (closure form; the EventHandler trait method is equivalent):

s_card.on_progress_info(|name, value| println!("{name}: {value}"));
top