Rust in PCAN-Basic: a memory-safe systems language joins the CAN toolbox
PCAN-Basic 5.1 supports Rust in the form of an FFI (Foreign Function Interface) module. This gives Rust developers direct access to the long-proven PCAN-Basic API.
Why Rust matters for CAN applications
Vehicle and machine software must be fast, reliable, maintainable, and secure all at once. As architectures become zonal and a growing share of development, test, diagnostics, logging, simulation, and gateway logic runs on PCs, the choice of languages and APIs matters more and more.
Memory-safety defects — buffer overruns, use-after-free, invalid pointer access, data races — cause crashes, unpredictable behavior, and security vulnerabilities. Traditional systems languages such as C and C++ offer a high level of control and performance, but they place a heavy responsibility on the developer and on the development process.
Rust addresses this problem with its ownership and borrowing rules, checked at compile time. In safe Rust, they rule out broad classes of memory and concurrency errors before the program even runs, without a garbage collector. Rust does not make an application automatically correct or certified, and FFI boundaries still require care; it does, however, reduce important implementation risks while retaining native-code performance and low-level control.
This is what makes Rust increasingly relevant for automotive tooling, test systems, diagnostics, data acquisition, gateways, and command-line utilities that communicate with CAN networks. With PCAN-Basic 5.1, Rust accesses PEAK's PC CAN hardware through the same API model as the other supported languages.
PCAN-Basic, the CAN development API
PCAN-Basic is PEAK's API for developing applications that communicate via CAN CC, CAN FD, and CAN XL. It provides the functions needed to communicate with PCAN hardware: channel initialization, bit rate configuration, message transmission and reception, status queries, hardware identification, trace recording, and other channel parameters. The architecture consists of the device driver and an interface library that provides access to the API functions; it is designed so that an application can be ported from one platform to another with few changes, under Windows 10 and 11 as well as under Linux.
PCAN-Basic already supports a broad range of languages: C++, C#, C++/CLR, Object Pascal, VB.NET, Java, and Python. Version 4 introduced CAN FD, version 5 CAN XL, and version 5.1 adds the Rust FFI module and its console examples. For the exact requirements (platform, Rust toolchain), refer to the current PCAN-Basic package and to the README files of the examples.
Capabilities useful to application developers include:
- CAN CC, CAN FD, and CAN XL communication through protocol-specific initialization, read, and write functions;
- multiple PEAK applications and one custom application simultaneously on the same physical channel;
- up to 16 channels per hardware type, and easy switching from one channel to another;
- driver-side receive queues, timestamped reception, channel status, and configurable receive events;
- API that can be used safely from multiple threads;
- recording in PCAN-Trace format and numerous parameters for identification, reception, and logging.
Rust in a nutshell
Rust is a compiled systems language, not a scripting language. It targets the same areas as C and C++: software with predictable performance, direct control over resources, and close interaction with the operating system or the hardware.
Its hallmark is the ownership model. Every value has an owner, and the compiler checks how values are moved, borrowed, shared, and released. Lifetimes describe the relationships between references, so that an invalid reference is rejected at compile time. These checks are particularly useful in multithreaded programs, where Rust's type system rules out many data races.
Error handling is just as explicit: an operation that can fail generally returns a Result value, and an optional value an Option. The calling code must therefore deliberately handle success, failure, and absence. Finally, Rust comes with Cargo, its build system and package manager, which brings together builds, dependencies, tests, examples, and documentation in a single workflow.
mod PCANBasic;
use crate::PCANBasic::*;
fn main() {
match Initialize(PCAN_USBBUS1, PCAN_BAUD_500K) {
Ok(_) => println!("PCAN-USB initialized successfully."),
Err(status) => println!("Error initializing PCAN-USB: {:?}", status)
}
}
Initializing a PCAN-USB channel in Rust. Safe code offers strong guarantees; a call that crosses the FFI boundary must still respect the native API contract.
What Rust support means
PCAN-Basic 5.1 adds Rust in the form of an FFI module, the mechanism by which Rust code calls the functions of a native library. In practical terms, the Rust layer exposes the proven PCAN-Basic function set to the application: it does not replace the PCAN driver, nor does it rewrite the API in pure Rust.
The distinction matters. Developers gain the Rust language, its project tooling, and its type checking around their application code. In return, they must deploy the correct PCAN-Basic library and driver, select compatible hardware and bit rates, check every returned status code, and follow the API's initialization and release rules.
Advantages for developers
- Performance without a garbage collector. Rust compiles to native code: it is well suited to continuous receive loops, high-rate data processing, test automation, and protocol tooling.
- Compile-time protection. Safe Rust rules out many invalid memory accesses and data races before execution, which reduces debugging effort without replacing system testing, code review, or functional safety processes.
- Explicit status and error handling. PCAN-Basic operations return a status code, which Rust's
Resultstyle encourages developers to convert into clear success and error paths. - Modern tooling. Cargo provides a consistent way to build, test, run the examples, manage dependencies, and automate continuous integration.
- A strong concurrency model. Rust lends itself to architectures that separate CAN reception, decoding, logging, user interface, and network forwarding into controlled threads or asynchronous tasks.
- Tools that are easy to distribute. Rust produces efficient standalone executables for manufacturing, after-sales service, validation, or diagnostics.
These advantages come at a price: ownership, borrowing, lifetimes, and trait-based abstractions differ from C, C++, C#, or Python. A team should plan for onboarding time and code review conventions.
The Rust examples supplied with PCAN-Basic
The supplied examples cover the operations that most CAN applications need:
- searching for an available channel;
- reading and writing hardware and channel parameters;
- manually reading and writing messages;
- reading messages with a dedicated thread;
- event-driven reception;
- creating a PCAN-Trace file.
It is better to start from the supplied example than to copy an excerpt from an article: it contains the exact module layout, constants, data structures, linking configuration, and error handling of the released version.
A first program, step by step
- select or look up an available PCAN channel;
- initialize it for the required protocol and bit rate (CAN CC, CAN FD, or CAN XL);
- check the returned status code before continuing;
- create the protocol-specific message structure;
- transmit with the corresponding write function;
- read until the receive queue is empty, processing the data and the timestamp;
- query or format errors for diagnostics;
- always release the channel at the end of the program.
The example below follows this sequence: it looks up a PCAN-USB channel, reads its capabilities, initializes it for CAN XL, CAN FD, or CAN CC depending on the hardware, transmits a message, drains the receive queue, and then releases the channel.
mod PCANBasic;
use crate::PCANBasic::*;
const BITRATE: TPCANBaudrate = PCAN_BAUD_500K;
const BITRATE_FD: &str = "\
f_clock_mhz=20, nom_brp=5, nom_tseg1=2, nom_tseg2=1, nom_sjw=1, \
data_brp=2, data_tseg1=3, data_tseg2=1, data_sjw=1";
const BITRATE_XL: &str = "\
f_clock=160000000, brp=1, nom_tseg1=255, nom_tseg2=64, nom_sjw=64, \
fd_tseg1=63, fd_tseg2=16, fd_sjw=16, fd_ssp_offset=0, \
xl_tseg1=10, xl_tseg2=9, xl_sjw=9, xl_ssp_offset=10, xl_error_signaling=1, xl_transceiver_mode_switch=0";
const MESSAGE: TPCANMsg = TPCANMsg { ID: 0x100, MSGTYPE: PCAN_MESSAGE_EXTENDED, LEN: 8, DATA: [0; 8] };
const MESSAGE_FD: TPCANMsgFD = TPCANMsgFD { ID: 0x100, MSGTYPE: PCAN_MESSAGE_FD | PCAN_MESSAGE_BRS, DLC: 15, DATA: [0; 64] };
const MESSAGE_XL: TPCANMsgXL = TPCANMsgXL { PID: 0x100, VCID: 0, AF: 0, RRS: 0, SEC: 0, SDT: 0, MSGTYPE: PCAN_MESSAGE_XL, DLC: 2047, DATA: [0; 2048] };
fn main() {
let parameters = format!("{}={}", LOOKUP_DEVICE_TYPE, "PCAN_USB");
let handle: TPCANHandle = match LookUpChannel(¶meters) {
Ok(handle) => { println!("Looked up channel"); handle }
Err(status) => { println!("Error looking up channel: {}", status); return; }
};
let features: u32 = match GetValueInt32(handle, PCAN_CHANNEL_FEATURES) {
Ok(features) => { println!("Retrieved features"); features }
Err(status) => { println!("Error retrieving features: {}", status); return; }
};
let is_fd = (features & FEATURE_FD_CAPABLE as u32) == FEATURE_FD_CAPABLE as u32;
let is_xl = (features & FEATURE_XL_CAPABLE as u32) == FEATURE_XL_CAPABLE as u32;
let initialize_result = match (is_xl, is_fd) {
(true, _) => InitializeXL(handle, BITRATE_XL),
(false, true) => InitializeFD(handle, BITRATE_FD),
(false, false) => Initialize(handle, BITRATE),
};
match initialize_result {
Ok(_) => println!("Initialized channel"),
Err(status) => { println!("Error initializing channel: {}", status); return; }
}
let write_result = match (is_xl, is_fd) {
(true, _) => WriteXL(handle, &mut MESSAGE_XL),
(false, true) => WriteFD(handle, &mut MESSAGE_FD),
(false, false) => Write(handle, &mut MESSAGE),
};
match write_result {
Ok(_) => println!("Wrote message"),
Err(status) => println!("Error writing message: {}", status),
}
loop {
let result = match (is_xl, is_fd) {
(true, _) => ReadXL(handle).map(|_| println!("Received XL message")),
(false, true) => ReadFD(handle).map(|_| println!("Received FD message")),
(false, false) => Read(handle).map(|_| println!("Received CC message")),
};
match result {
Ok(_) => continue,
Err(status) if status == PCAN_ERROR_QRCVEMPTY => break,
Err(status) => { println!("Error reading message: {}", status); return; }
}
}
match Uninitialize(handle) {
Ok(_) => println!("Uninitialized channel"),
Err(status) => println!("Error uninitializing channel: {}", status),
}
}
For a production application, it is advisable to wrap this native call sequence in a small Rust abstraction that:
- stores the channel and the protocol mode together, so that CAN CC, CAN FD, and CAN XL functions are not mixed up by accident;
- converts every status code into a meaningful Rust error type, including the PEAK error text;
- releases the channel through a guard object (
Dropimplementation), while still allowing an explicit shutdown; - validates IDs, message types, data lengths, and bit rate strings before crossing the FFI boundary;
- drains the receive queue after a notification: an event signals that data is available, it does not replace the read operation;
- confines
unsafecode to the FFI calls and exposes only safe methods to the rest of the program.
Typical use cases
- Automotive test and validation: ECU stimulation, residual bus simulation, automated regression tests, HiL integration, measurement utilities.
- Diagnostics and service tools: focused command-line or desktop tools for reading status, issuing diagnostic requests, and capturing evidence.
- Data acquisition and logging: high-rate reception, timestamp processing, filtering, conversion, creation of PCAN-Trace files.
- Gateways and bridges: forwarding selected CAN traffic to Ethernet, cloud services, files, or databases.
- Manufacturing and end-of-line: robust utilities for configuration, identification, flashing, verification, and result collection.
- Developer tooling: frame generators, protocol analyzers, replay tools, fuzzing harnesses.
- Embedded and IoT ecosystems: companion tools for teams that already use Rust on their embedded targets.
What Rust guarantees, and what it does not
Rust rules out many memory and concurrency defects in safe code, but reliable automotive software still depends on correct requirements, protocol design, timing behavior, hardware configuration, network topology, error handling, and verification. Using Rust or PCAN-Basic does not by itself establish functional safety, cybersecurity compliance, or real-time guarantees.
The FFI module necessarily connects safe Rust code to a native API. It is therefore necessary to keep unsafe operations small, review the API contract carefully, validate lengths and pointers, and build a safe wrapper that accurately reflects the lifecycle of a PCAN-Basic channel. This is not a constraint specific to PCAN-Basic: it is the rule whenever Rust integrates with a mature native library.
In summary
More and more engineers want to write their PC-based CAN applications in the language they already use elsewhere. PCAN-Basic 5.1 meets that demand with a Rust FFI module and ready-to-use examples. C and C++ developers gain a way to retain native performance while handing many memory and concurrency checks over to the compiler; others get modern tooling and explicit error handling. And no one starts from a blank page: simply take the official examples, verify communication with a PCAN interface, and then evolve the whole into a safe architecture for CAN CC, CAN FD, or CAN XL.