Interoperating with C APIs in C++ can be achieved by wrapping C data types with C++ constructs. One common scenario involves using `std::pair` to hold two related values. When working with C APIs that do not directly support C++ constructs, you can define a C-compatible struct that mimics the behavior of `std::pair`, facilitating smoother integration.
In this example, we will define a C-compatible structure that represents a pair of integers, and we will also show how to use it with C functions.
// C-compatible Pair struct
typedef struct {
int first;
int second;
} IntPair;
// Function to create a pair
IntPair create_pair(int a, int b) {
IntPair p;
p.first = a;
p.second = b;
return p;
}
// Function to print pair values
void print_pair(IntPair p) {
printf("First: %d, Second: %d\n", p.first, p.second);
}
// Example usage
#include
int main() {
IntPair myPair = create_pair(1, 2);
print_pair(myPair);
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?