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

Interoperating with C APIs using C++'s std::array can be straightforward and efficient. While std::array is a C++ feature that provides a statically sized array, C APIs typically utilize basic C arrays. The key to interoperation is to properly manage the data types and conversion between them.

C++, std::array, C API, interoperability, C arrays, types, conversion

This article provides an overview of how to use std::array in C++ when interacting with C APIs, highlighting conversion methods and data handling.


#include <array>
#include <iostream>

// A C function that takes a pointer to an array and its size
extern "C" void process_array(int* arr, size_t size) {
    for (size_t i = 0; i < size; ++i) {
        arr[i] *= 2; // Example processing: double each element
    }
}

int main() {
    // Define a std::array
    std::array myArray = {1, 2, 3, 4, 5};
    
    // Call the C function with the data from std::array
    process_array(myArray.data(), myArray.size());
    
    // Print the modified array
    for (const auto& elem : myArray) {
        std::cout << elem << " "; // Output: 2 4 6 8 10
    }
    return 0;
} 
    

C++ std::array C API interoperability C arrays types conversion