How do I interoperate with C APIs std::span in C++?

Interoperating with C APIs in C++ can be challenging, particularly when dealing with data structures. One useful tool for handling array-like data is std::span, introduced in C++20. This lightweight wrapper allows you to work with contiguous sequences of data easily. Below is an example that demonstrates how to use std::span to interact with a C API.

#include #include extern "C" { // C API function that takes an array and its size void process_data(int *data, size_t size) { for (size_t i = 0; i < size; ++i) { // Simple processing: print each element std::cout << "Processing: " << data[i] << std::endl; } } } int main() { int arr[] = {1, 2, 3, 4, 5}; std::span span(arr, sizeof(arr)/sizeof(arr[0])); // Pass the span to the C API process_data(span.data(), span.size()); return 0; }

C++ std::span C API interoperability array-like data