xilinx-power-monitor
English | 中文
A comprehensive power monitoring library for NVIDIA Xilinx devices, available in multiple programming languages.
Features
- Real-time power consumption monitoring
- Support for multiple programming languages (C/C++, Rust, Python)
- Easy installation through package managers
- Low-level access to power metrics
- Cross-platform support for Xilinx devices
Installation
Python
Rust
Add to your Cargo.toml:
[]
= "0.0.3"
C/C++
For Debian/Ubuntu systems:
Download the pre-built .deb package from the Releases page:
For RPM-based systems (CentOS/RHEL/Fedora/PetaLinux):
Download the pre-built .rpm package from the Releases page:
# For DNF-based systems (Fedora, RHEL 8+, Rocky Linux)
# For YUM-based systems (CentOS 7, RHEL 7)
Using CMake:
Or use CMake to find and link the library in your project:
find_package(xlnpwmon REQUIRED)
target_link_libraries(your_target PRIVATE xlnpwmon::xlnpwmon) # Use shared library
# or
target_link_libraries(your_target PRIVATE xlnpwmon::static) # Use static library
# For C++ bindings
target_link_libraries(your_target PRIVATE xlnpwmon::xlnpwmon_cpp) # Use shared library
# or
target_link_libraries(your_target PRIVATE xlnpwmon::static_cpp) # Use static library
Usage
Python
Quick Start: Get Instantaneous Readings
This shows how to get the current total power consumption, voltage, and current readings directly from the device.
# Create a power monitor instance
=
# Get the latest data snapshot
=
# Access total readings
=
# Access individual sensor readings
This example demonstrates how to start background power sampling before a task, stop it afterwards, and retrieve detailed statistics (min, max, average power, total energy) for the monitoring period.
# Using numpy for a sample CPU-intensive task
"""Simulate a CPU-intensive task"""
# Reduced size for a quicker example run
= 2000
=
=
# Perform matrix multiplication
=
"""Monitor power consumption during task execution"""
# Create a power monitor instance
=
# Optional: Set the sampling frequency (e.g., 1000Hz)
# Higher frequencies provide more granular data but increase overhead.
# Check library documentation or device limits for valid/optimal values.
# Reset statistics before starting a new monitoring period
# Start background sampling
# --- Execute the task you want to monitor ---
# --- Task finished ---
# Optional: Wait briefly to ensure last samples are captured,
# depends on task duration and sampling frequency.
# Stop background sampling
# Get collected statistics
=
# --- Print the collected statistics ---
# Print total power consumption statistics
=
# Use .get() for safety in case some stats weren't computed
# Print power consumption information for each sensor/channel
=
# --- Run the monitoring example ---
Rust
First, add xlnpwmon as a dependency in your Cargo.toml. Adjust the path or version as needed.
[]
= "0.0.3"
# The examples also use these crates:
= "0.15" # For matrix example
= "0.8" # For matrix example
Quick Start: Get Latest Sensor Readings
This example shows how to initialize the monitor and get a single snapshot of the current power, voltage, and current, for both the total and individual sensors. Note the use of unsafe to access per-sensor data returned via raw pointers.
use ;
use slice;
This example demonstrates starting background sampling, running a CPU-intensive task (matrix multiplication across threads), stopping sampling, and retrieving detailed statistics. It highlights error handling with Result and the necessary unsafe block for accessing per-sensor statistics.
Dependencies needed for this example:
[]
= { = "0.0.3" } # Adjust as needed
= "0.15"
= "0.8"
use ;
use ;
use Array2;
use Rng;
// Example task parameters (adjust as needed)
const MATRIX_SIZE: usize = 1000; // Size of matrices
const NUM_THREADS: usize = 4; // Number of concurrent tasks
const NUM_ITERATIONS: usize = 5; // Workload per thread
/// Example CPU-intensive task using ndarray for matrix multiplication
// Use Box<dyn StdError> for flexible error handling in main
C/C++
Compilation
-
Include Header: Add the following line to your C source files:
// Or adjust the path based on your project structure: // #include "path/to/include/xlnpwmon/xlnpwmon.h" -
Link Library: When compiling, you need to link against the
libxlnpwmonlibrary. Assuming the library and header files are installed in standard system paths or paths specified via-Land-I:# Basic compilation # If library/includes are in custom locations: # gcc your_program.c -o your_program -I/path/to/xlnpwmon/include -L/path/to/xlnpwmon/lib -lxlnpwmon # You can use pkg-config to find the library and include paths: # gcc your_program.c -o your_program -lxlnpwmon `pkg-config --libs --cflags xlnpwmon` # Add other libraries if needed (like pthread for threading, m for math, omp for OpenMP) # Example with OpenMP (like the advanced example below): # gcc your_program.c -o your_program -I/path/to/include -L/path/to/lib -lxlnpwmon -fopenmp -lm
Quick Start: Get Latest Sensor Readings
This example demonstrates the basic lifecycle: initialize the library, get a single snapshot of current sensor readings, print them, and perform the mandatory cleanup.
int
This example demonstrates the complete workflow for monitoring power consumption during a specific task. It initializes the library, configures and starts sampling, executes a CPU-intensive task (using OpenMP for parallelization), stops sampling, retrieves the collected statistics, prints them, and cleans up.
Note: Compile this example with OpenMP support enabled (e.g., gcc -fopenmp ...)
// Example CPU-intensive task (Matrix Multiplication using OpenMP)
void
int
C++
Compilation
-
Include Header: Use the C++ wrapper header file in your source code:
-
Link Library: Compile your C++ code (ensuring C++14 or later standard is enabled) and link against the underlying
libxlnpwmonC library:# Compile using g++ with C++14 support # If library/includes are in custom locations: # g++ your_program.cpp -o your_program -std=c++14 -I/path/to/xlnpwmon/include -L/path/to/xlnpwmon/lib -lxlnpwmon # Add other necessary flags (e.g., -pthread for std::thread, Eigen paths/libs) # g++ your_program.cpp -o your_program -std=c++14 -I/path/to/eigen -I/path/to/include -L/path/to/lib -lxlnpwmon -pthread
Key Features of the C++ Wrapper:
- RAII (Resource Acquisition Is Initialization): The
xlnpwmon::PowerMonitorobject automatically initializes the library (pm_init) on creation and cleans up resources (pm_cleanup) upon destruction (when it goes out of scope). No manual cleanup calls are needed. - Exception Safety: C API errors are converted into
std::runtime_errorexceptions, allowing for standard C++ error handling usingtry...catchblocks.
Quick Start: Get Latest Sensor Readings (C++ Wrapper)
This example demonstrates initializing the monitor using the C++ wrapper, getting a snapshot of current readings, printing them, and letting RAII handle cleanup.
// Helper function to safely convert C char array (potentially not null-terminated) to std::string
std::string
int
This example uses the xlnpwmon::PowerMonitor C++ wrapper, std::thread, and exception handling to monitor power consumption during a parallel matrix multiplication task (using Eigen).
Example Dependencies: Eigen library, C++11 thread support (-pthread).
// Example Task Parameters
const int MATRIX_SIZE = 1000; // Adjust based on system memory/CPU
const int NUM_THREADS = 4; // Number of threads for the task
const int NUM_ITERATIONS = 5; // Workload per thread
// Helper function to safely convert C char array to std::string
std::string
// Example CPU-intensive task using Eigen library
void
int
API Documentation
Python
Here are the primary methods available on the PowerMonitor class:
"""
Initializes the connection to the power monitor hardware (e.g., INA3221 via I2C).
May raise an exception if the device cannot be found or accessed.
"""
pass # Actual implementation omitted
"""
Reads the device for the current total power consumption across relevant channels.
Returns:
float: Instantaneous total power in Watts.
"""
pass
"""
Reads the device for the current bus voltage (typically from a specific channel like VIN).
Returns:
float: Instantaneous voltage in Volts.
"""
pass
"""
Reads the device for the current total shunt current across relevant channels.
Returns:
float: Instantaneous total current in Amperes.
"""
pass
"""
Sets the target frequency for background sampling when monitoring.
Args:
frequency_hz (int): Desired samples per second (e.g., 100, 1000).
The actual achievable rate may be limited by hardware/system load.
"""
pass
"""
Starts a background thread or process to continuously sample power data
at the configured frequency. Statistics are accumulated internally.
Requires `stop_sampling()` to be called later.
"""
pass
"""
Stops the background sampling process started by `start_sampling()`.
"""
pass
"""
Clears all internally accumulated statistics (min, max, sum for average, energy, count).
Call this before `start_sampling()` to measure a specific interval.
"""
pass
"""
Retrieves the power statistics collected since the last reset or initialization.
Best used after `start_sampling()` and `stop_sampling()`.
Returns:
dict: A dictionary containing aggregated ('total') and per-sensor ('sensors')
statistics. See the structure documented below. Returns empty or
partially filled dict if sampling didn't run or failed.
"""
pass
"""
Retrieves the latest power consumption summary for PS, PL, and Total.
Returns:
dict: A dictionary containing:
- 'ps_total_power' (float): Processing System total power in Watts
- 'pl_total_power' (float): Programmable Logic total power in Watts
- 'total_power' (float): Total system power in Watts
"""
pass
"""
Retrieves power statistics summary for PS, PL, and Total.
Returns:
dict: A dictionary containing statistics for each subsystem:
- 'ps_total_power' (dict): PS power stats with min, max, avg, total, count
- 'pl_total_power' (dict): PL power stats with min, max, avg, total, count
- 'total_power' (dict): Total power stats with min, max, avg, total, count
"""
pass
The get_statistics() method returns a dictionary structured as follows:
Important Notes:
- The exact sensor names available in the
'sensors'list depend on the specific Xilinx board model and how the INA3221 channels are configured and named within the library. - The
'total'energy is typically calculated based on the average power (avg) and the duration of the sampling period (derived fromcountand the sampling frequency). - If
start_sampling()/stop_sampling()were not used, or if data collection failed, the returned dictionary might be empty, partially filled, or contain default values like0orNaN. Robust code should handle potentially missing keys or non-numeric values (e.g., using.get()with defaults as shown in the monitoring example).
Rust
Structs & Enums:
PowerMonitor: The main interface to the library. Manages the C handle and ensures cleanup via theDroptrait.SensorType: Enum identifying the type of sensor (Unknown,I2C,System).SensorData: Holds instantaneous data for one sensor.name: [u8; 64]: Sensor name (C string, needs conversion).type_: SensorType: Type of the sensor.voltage: f64,current: f64,power: f64: Measured values.online: bool: Whether the sensor is currently readable.status: [u8; 32]: Status message (C string, needs conversion).warning_threshold: f64,critical_threshold: f64: Thresholds in Watts.
Stats: Holds statistics (min, max, avg, total, count) for a single metric (like power, voltage, or current).SensorStats: Holds statistics for one sensor, containingStatsfor voltage, current, and power.name: [u8; 64]: Sensor name (C string, needs conversion).voltage: Stats,current: Stats,power: Stats.
PowerData: Holds instantaneous data snapshot.total: SensorData: Aggregated data across relevant sensors.sensors: *mut SensorData: Raw pointer to an array ofSensorData. Requiresunsafeto access.sensor_count: i32: Number of elements in thesensorsarray.
PowerStats: Holds accumulated statistics.total: SensorStats: Aggregated stats across relevant sensors.sensors: *mut SensorStats: Raw pointer to an array ofSensorStats. Requiresunsafeto access.sensor_count: i32: Number of elements in thesensorsarray.
Error: Enum representing possible error codes from the underlying C library (e.g.,InitFailed,NotRunning,NoSensors). ImplementsFrom<i32>andInto<i32>.
PowerMonitor Methods:
PowerMonitor::new() -> Result<Self, Error>: Creates and initializes the monitor instance. Connects to hardware.set_sampling_frequency(&self, frequency_hz: i32) -> Result<(), Error>: Sets the target sampling frequency in Hz for background monitoring.get_sampling_frequency(&self) -> Result<i32, Error>: Gets the currently configured sampling frequency.start_sampling(&self) -> Result<(), Error>: Starts background sampling thread. Statistics begin accumulating.stop_sampling(&self) -> Result<(), Error>: Stops the background sampling thread.is_sampling(&self) -> Result<bool, Error>: Returnstrueif background sampling is currently active.get_latest_data(&self) -> Result<PowerData, Error>: Fetches the most recent instantaneous readings. Return value (PowerData) contains raw pointers requiringunsafeaccess. See "Data Structures & Safety Notes".get_statistics(&self) -> Result<PowerStats, Error>: Fetches the statistics accumulated since the lastreset_statistics()or initialization. Return value (PowerStats) contains raw pointers requiringunsafeaccess. See "Data Structures & Safety Notes".reset_statistics(&self) -> Result<(), Error>: Resets all internal statistics counters (min, max, avg, total, count) to zero.get_sensor_count(&self) -> Result<i32, Error>: Returns the number of sensors detected by the library.get_sensor_names(&self) -> Result<Vec<String>, Error>: Returns aVec<String>containing the names of all detected sensors. Handles C string conversion internally.
Error Handling:
- All methods that interact with the C library return
Result<T, xlnpwmon::Error>. - Use standard Rust error handling (e.g.,
match,if let Ok/Err,?operator) to check for and handle potential errors like device access failures, invalid states, etc.
Resource Management:
- The
PowerMonitorstruct implements theDroptrait. When aPowerMonitorinstance goes out of scope, itsdropmethod is automatically called, which in turn calls the C library's cleanup function (pm_cleanup). You do not need to call a cleanup function manually.
Working with Raw Pointers in PowerData and PowerStats
The C library returns arrays of sensor data/statistics via raw pointers (*mut SensorData or *mut SensorStats). The Rust wrapper exposes these directly within the PowerData and PowerStats structs.
Accessing this data requires unsafe blocks in your code. The recommended way is to create a temporary, safe Rust slice from the raw pointer and count:
use slice;
use ; // Assuming these are defined
The same pattern applies when accessing sensors within a PowerData struct.
Working with C Strings (name and status fields)
Struct fields like name ([u8; 64]) and status ([u8; 32]) are fixed-size byte arrays intended to hold C-style null-terminated strings (or potentially just padded with nulls).
To safely convert them to a Rust String:
- Use
String::from_utf8_lossy(): This handles potential invalid UTF-8 sequences gracefully by replacing them with the character. - Use
.trim_matches('\0'): This removes any leading/trailing null bytes used for padding or termination in the C buffer.
use SensorData; // Assuming SensorData has a name: [u8; 64]
Overall Safety
- This Rust wrapper aims to be safe where possible (using
Result,Dropfor cleanup). - However, direct interaction with the C library via FFI inherently involves
unsafeoperations, especially when dealing with raw pointers returned from C (get_latest_data,get_statistics). - It is the user's responsibility to understand the memory management and lifetime guarantees provided by the underlying C library when working within
unsafeblocks. Incorrect assumptions can lead to undefined behavior (crashes, memory corruption). Always consult the C library's documentation if available.
C/C++
Handle Type:
pm_handle_t: An opaque pointer (struct pm_handle_s*) representing an initialized instance of the library. Returned bypm_init()and required by most other functions. Must be passed topm_cleanup()to release resources.
Enums:
pm_error_t: Integer error codes.PM_SUCCESS(0) indicates success. Negative values indicate errors. Seepm_error_string()to get descriptions.PM_SUCCESS = 0PM_ERROR_INIT_FAILED = -1PM_ERROR_NOT_INITIALIZED = -2PM_ERROR_ALREADY_RUNNING = -3PM_ERROR_NOT_RUNNING = -4PM_ERROR_INVALID_FREQUENCY = -5PM_ERROR_NO_SENSORS = -6PM_ERROR_FILE_ACCESS = -7PM_ERROR_MEMORY = -8PM_ERROR_THREAD = -9
pm_sensor_type_t: Identifies the type of power sensor.PM_SENSOR_TYPE_UNKNOWN = 0PM_SENSOR_TYPE_I2C = 1(e.g., INA3221)PM_SENSOR_TYPE_SYSTEM = 2(e.g., sysfs power supply class)
Data Structures:
pm_sensor_data_t: Holds instantaneous data for a single sensor.char name[64]: Null-terminated sensor name.pm_sensor_type_t type: Sensor type.double voltage,current,power: Measured values (V, A, W).bool online: Indicates if the sensor is currently readable.char status[32]: Null-terminated status string (e.g., "OK").double warning_threshold,critical_threshold: Power thresholds (W).
pm_stats_t: Holds basic statistics for a metric.double min,max,avg: Min, Max, Average values.double total: Sum of values (can be used to calculate energy for power: Energy = Avg Power * Duration).uint64_t count: Number of samples collected.
pm_sensor_stats_t: Holds statistics for a single sensor.char name[64]: Null-terminated sensor name.pm_stats_t voltage,current,power: Statistics for each metric.
pm_power_data_t: Structure filled bypm_get_latest_data.pm_sensor_data_t total: Aggregated instantaneous data.pm_sensor_data_t* sensors: Pointer to an array of individual sensor data. Memory is managed by the library. The pointer is valid until the next relevant library call orpm_cleanup. Do not free this pointer.int sensor_count: Number of valid elements in thesensorsarray.
pm_power_stats_t: Structure filled bypm_get_statistics.pm_sensor_stats_t total: Aggregated statistics.pm_sensor_stats_t* sensors: Pointer to an array of individual sensor statistics. Memory is managed by the library. The pointer is valid until the next relevant library call orpm_cleanup. Do not free this pointer.int sensor_count: Number of valid elements in thesensorsarray.
Core Functions:
pm_error_t pm_init(pm_handle_t* handle):- Initializes the library, discovers sensors, allocates resources.
- Stores the opaque library instance handle at the address provided by
handle. - Must be called first. Returns
PM_SUCCESSon success.
pm_error_t pm_cleanup(pm_handle_t handle):- Stops sampling (if active) and frees all resources associated with the
handle. - Must be called when finished with the library to prevent resource leaks.
- Stops sampling (if active) and frees all resources associated with the
const char* pm_error_string(pm_error_t error):- Returns a constant, human-readable string describing the given error code. Do not modify or free the returned string.
Sampling Control & Status:
pm_error_t pm_set_sampling_frequency(pm_handle_t handle, int frequency_hz):- Sets the target sampling frequency (in Hz) for the background monitoring thread. Must be > 0.
pm_error_t pm_get_sampling_frequency(pm_handle_t handle, int* frequency_hz):- Retrieves the currently configured sampling frequency, storing it at the address
frequency_hz.
- Retrieves the currently configured sampling frequency, storing it at the address
pm_error_t pm_start_sampling(pm_handle_t handle):- Starts the background sampling thread. Statistics begin accumulating. Returns
PM_ERROR_ALREADY_RUNNINGif already started.
- Starts the background sampling thread. Statistics begin accumulating. Returns
pm_error_t pm_stop_sampling(pm_handle_t handle):- Stops the background sampling thread. Returns
PM_ERROR_NOT_RUNNINGif not running.
- Stops the background sampling thread. Returns
pm_error_t pm_is_sampling(pm_handle_t handle, bool* is_sampling):- Checks if the background sampling thread is active, storing the result (
trueorfalse) at the addressis_sampling.
- Checks if the background sampling thread is active, storing the result (
Data & Statistics Retrieval:
pm_error_t pm_get_latest_data(pm_handle_t handle, pm_power_data_t* data):- Fills the user-provided
datastructure with the most recent instantaneous sensor readings. - The
data->sensorspointer will point to an internal library buffer.
- Fills the user-provided
pm_error_t pm_get_statistics(pm_handle_t handle, pm_power_stats_t* stats):- Fills the user-provided
statsstructure with statistics accumulated since the last reset. - The
stats->sensorspointer will point to an internal library buffer.
- Fills the user-provided
pm_error_t pm_reset_statistics(pm_handle_t handle):- Resets all accumulated statistics (min, max, avg, total, count) to zero.
Sensor Information:
pm_error_t pm_get_sensor_count(pm_handle_t handle, int* count):- Gets the total number of sensors detected by the library.
pm_error_t pm_get_sensor_names(pm_handle_t handle, char** names, int* count):- Fills a caller-allocated array of C strings (
char* names[]) with the names of detected sensors. names: Pointer to an array ofchar*. The caller must allocate this array. Eachchar*in the array must also point to a caller-allocated buffer (e.g.,char name_buffer[64]) large enough to hold a sensor name.count:[inout]parameter. On input, points to the allocated size of thenamesarray. On output, points to the actual number of names written.- Note: This function requires careful memory management by the caller. Accessing names via
pm_get_latest_dataorpm_get_statistics(using thesensors[i].namefield) is often simpler as the library manages those strings.
- Fills a caller-allocated array of C strings (
C++ Bindings
Namespace: xlnpwmon
Main Class: PowerMonitor
- Description: An RAII wrapper class for managing the
xlnpwmonC library. It handles initialization (pm_init) in its constructor and cleanup (pm_cleanup) in its destructor automatically. It converts C API error codes intostd::runtime_errorexceptions. - Resource Management: Non-copyable, but movable. Uses
std::unique_ptrwith a custom deleter for the C handle (pm_handle_t). - Constructor:
PowerMonitor()- Initializes the library connection.
- Throws:
std::runtime_errorifpm_initfails. The exception'swhat()message contains the error description frompm_error_string.
- Destructor:
~PowerMonitor()- Automatically calls
pm_cleanupon the managed C handle.
- Automatically calls
- Methods:
void setSamplingFrequency(int frequency_hz)- Sets the background sampling frequency (Hz).
- Throws:
std::runtime_erroron C API failure.
int getSamplingFrequency() const- Gets the current sampling frequency (Hz).
- Throws:
std::runtime_erroron C API failure.
void startSampling()- Starts the background sampling thread.
- Throws:
std::runtime_erroron C API failure (e.g., already running).
void stopSampling()- Stops the background sampling thread.
- Throws:
std::runtime_erroron C API failure (e.g., not running).
bool isSampling() const- Checks if sampling is currently active.
- Throws:
std::runtime_erroron C API failure.
PowerData getLatestData() const- Gets the most recent instantaneous sensor readings.
- Returns: A
PowerDataobject containing the snapshot. - Throws:
std::runtime_erroron C API failure. - Note: See
PowerDatadescription and Safety Notes regarding pointer validity.
PowerStats getStatistics() const- Gets the statistics accumulated since the last reset.
- Returns: A
PowerStatsobject containing the statistics. - Throws:
std::runtime_erroron C API failure. - Note: See
PowerStatsdescription and Safety Notes regarding pointer validity.
void resetStatistics()- Resets all internal accumulated statistics.
- Throws:
std::runtime_erroron C API failure.
int getSensorCount() const- Gets the number of detected sensors.
- Throws:
std::runtime_erroron C API failure.
std::vector<std::string> getSensorNames() const- Gets the names of all detected sensors. Handles C memory management and string conversion.
- Returns: A
std::vector<std::string>containing the sensor names. - Throws:
std::runtime_erroron C API failure.
Data Wrapper Classes:
PowerData/PowerStats- Description: Thin wrappers around the C structs
pm_power_data_tandpm_power_stats_t, primarily returned bygetLatestDataandgetStatistics. They are non-copyable but movable. - Memory: They hold a copy of the
totalC struct member and the raw C pointer (sensors) along with thesensor_count. They do NOT manage the memory pointed to by thesensorspointer. That memory is owned by the underlying C library. - Getters:
const pm_sensor_data_t& getTotal() const(forPowerData)const pm_sensor_stats_t& getTotal() const(forPowerStats)- Returns a const reference to the copied
totaldata/statistics struct.
- Returns a const reference to the copied
const pm_sensor_data_t* getSensors() const(forPowerData)const pm_sensor_stats_t* getSensors() const(forPowerStats)- Returns the raw C pointer to the array of per-sensor data/statistics. See Safety Notes.
int getSensorCount() const: Returns the number of elements pointed to bygetSensors().
- Description: Thin wrappers around the C structs
Underlying C Structs:
- The C++ wrapper provides access to data via the C structs (
pm_sensor_data_t,pm_stats_t,pm_sensor_stats_t). Refer to the C API documentation for detailed field descriptions within these structs.
- RAII & Exceptions: The
PowerMonitorclass significantly improves safety by automating resource cleanup (pm_cleanup) through its destructor (RAII) and by converting C error codes into C++ exceptions (std::runtime_error). Always usetry...catchblocks when interacting withPowerMonitormethods. - Pointer Validity (
getSensors()): ThePowerDataandPowerStatsobjects returned bygetLatestData()andgetStatistics()contain raw C pointers to arrays (sensors). Crucially, the C++ wrapper classes (PowerData,PowerStats) do NOT manage the lifetime of the memory these pointers point to. This memory is managed by the C library.- Assumption: The memory pointed to by
getSensors()is typically valid only temporarily, likely until the next non-const call to thePowerMonitorobject or until thePowerMonitorobject is destroyed. - Guideline: Access the data through the pointer returned by
getSensors()immediately after the call togetLatestData()orgetStatistics(), within the same scope. Do not store this raw pointer for later use, as it may become invalid (dangling pointer).
- Assumption: The memory pointed to by
- C String Handling: Data structures contain C-style fixed-size character arrays (e.g.,
name[64],status[32]). Use safe methods (like thec_char_to_stringhelper in the examples usingstrnlen) to convert these tostd::stringto avoid buffer over-reads, especially if null termination is not guaranteed within the fixed size.
Building from Source
Prerequisites
- CMake 3.10 or higher
- C++ compiler with C++17 support
- Python 3.8 or higher (for Python bindings)
- Rust toolchain (for Rust bindings)
Build Steps
C Library and C++ Bindings
&&
Python Bindings
# or you need to build wheel
# the result will be in dist/
Rust Bindings
# copy c headers and sources to rust vendor directory
# build rust crate
Contributing
We welcome contributions! Please see our CONTRIBUTING.md for detailed information about:
- Project architecture and implementation details
- Development setup and guidelines
- Code style and testing requirements
- Pull request process
- Common development tasks
- Release process
License
This project is licensed under the BSD 3-Clause License License - see the LICENSE file for details.
Acknowledgments
- NVIDIA Xilinx team for their excellent hardware
- All contributors who have helped with this project
- xilinx_stats