qiskit/crates/cext
Matthew Treinish 86e6b72066
Bump PyO3 to 0.24.1 and numpy to 0.24.0 (#14149)
This commit bumps the PyO3 version we use in Qiskit to the latest
pyo3 release 0.24.1. Luckily this time there don't seem to be any API
changes required to upgrade so it's a straight version bump.
2025-04-01 16:47:43 +00:00
..
src Make C API docs publishable (#14101) 2025-03-28 21:31:28 +00:00
Cargo.toml Bump PyO3 to 0.24.1 and numpy to 0.24.0 (#14149) 2025-04-01 16:47:43 +00:00
README.md Attempt to fix MacOS PGO build (#13992) 2025-03-14 19:04:54 +00:00
build.rs Use `cbindgen` via Rust API (#14013) 2025-03-31 14:01:17 +00:00
cbindgen.toml Use `cbindgen` via Rust API (#14013) 2025-03-31 14:01:17 +00:00

README.md

qiskit-cext

This crate contains the bindings for Qiskit's C API.

Building the library

The C bindings are compiled into a shared library, which can be built along with the header file by running

make c

in the root of the repository. The header file, qiskit.h, is generated using cbindgen and stored in dist/c/include. Similarly, the libqiskit shared library is stored in dist/c/lib.

You can ask Make to build only the header file with make cheader, or only the shared-object library with make clib. Instead of make clib the shared C library can also be compiled via

cargo rustc --release --crate-type cdylib -p qiskit-cext

note that the crate-type should be defined explicitly to build the cdylib instead of the rlib default.

The following example uses the header to build a 100-qubit observable:

#include <complex.h>
#include <qiskit.h>
#include <stdint.h>
#include <stdio.h>

int main(int argc, char *argv[]) {
    // build a 100-qubit empty observable
    uint32_t num_qubits = 100;
    QkObs *obs = qk_obs_zero(num_qubits);

    // add the term 2 * (X0 Y1 Z2) to the observable
    complex double coeff = 2;
    QkBitTerm bit_terms[3] = {QkBitTerm_X, QkBitTerm_Y, QkBitTerm_Z};
    uint32_t indices[3] = {0, 1, 2};
    QkObsTerm term = {coeff, 3, bit_terms, indices, num_qubits};
    qk_obs_add_term(obs, &term);

    // print some properties
    printf("num_qubits: %u\n", qk_obs_num_qubits(obs));
    printf("num_terms: %lu\n", qk_obs_num_terms(obs));

    // free the memory allocated for the observable
    qk_obs_free(obs);

    return 0;
}

Refer to the C API documentation for more information and examples.

Compiling

The above program can be compiled by including the header and linking to the qiskit library, which are located in the standard directory configuration whose root is dist/c.

make c
gcc program.c -I$/path/to/dist/c/include -lqiskit -L/path/to/dist/c/lib

The example program will then output

./a.out
num_qubits: 100
num_terms: 1