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;
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?