Is there any way/trick to pass std::set to a C API which expects C Array?

No, but you could fill an array with your set contents pretty quickly. For example, assuming mySet is a set of the same type as YOUR_TYPENAME.

No, but you could fill an array with your set contents pretty quickly. For example, assuming mySet is a set of the same type as YOUR_TYPENAME: YOUR_TYPENAME arr* = new YOUR_TYPENAMEmySet.size(); std::copy(mySet.begin(), mySet.end(), arr); Then just pass arr into the C API.

– Mark Ransom Oct 3 at 15:09 1 +1. I like this solution more than the vector one, because it does not require an intermediary type. But, as you are dealing with a C API I'd allocate the array with malloc (or a derivate), especially if the array is likely to be freed inside the API.

– Constantinius Oct 3 at 15:09 @Constantinius, I agree that malloc would be more appropriate than new if the ownership was passed to the API, but I wouldn't expect that to be a common case. Not sure what you mean by an intermediary type, in both cases you're creating an array of the element type. Vector leaves you with fewer memory management issues, especially if there's any chance that an exception might be thrown somewhere.

– Mark Ransom Oct 3 at 15:21 1 @Constantinius: What does "require an intermediary type" have to do with anything? Guess what: new YOUR_TYPENAME... has a type too! Std::vector is more appropriate.

The question says nothing about free'ing. – GMan Oct 3 at 15:26 1 @Constantinius, this is purely academic since we don't know the specifics of the API, but in general, if the API is going to free memory you allocate, it must specify exactly how should you allocate it. Malloc and free won't do much good if two CRTs happen to be used (and obviously, neither will new and delete).

So in case of memory ownership transfer across API boundaries, there are no best practices - just strict definitions (given you can't change the API). – eran Oct 3 at 16:23.

Not directly, but you can first convert the set to a vector (called, say, vec), and then pass &vec0, which is a pointer to the first element of the internal vector array.

For completeness, the vector alternative to the currently accepted answer would look like this: { std::vector arr(mySet.begin(), mySet.end()); Your_C_API(&arr0); // memory implicitly freed on next line } I prefer this style because: It takes one fewer lines, and It eliminates a class of mistakes that I often make (that is, forgetting to delete).

I cant really gove you an answer,but what I can give you is a way to a solution, that is you have to find the anglde that you relate to or peaks your interest. A good paper is one that people get drawn into because it reaches them ln some way.As for me WW11 to me, I think of the holocaust and the effect it had on the survivors, their families and those who stood by and did nothing until it was too late.

Related Questions