I am attempting to write a C wrapper for some C++ data structures. Right now I've got the following in foo.cpp
typedef std::map<unsigned int, void *> _Map;
extern "C"{
void* map_create()
{
return reinterpret_cast<void*> (new _Map);
}
void map_put(void *map, unsigned int k, void *v)
{
Map *m = reinterpret_cast<_Map *> (map);
m->insert(std::pair<unsigned int, void *>(k, v));
}
}
In foo.h
I've got
#ifdef __cplusplus
#define EXTERNC extern "C"
#else
#define EXTERNC
#endif
typedef void *Map;
EXTERNC void *map_create();
EXTERNC void map_put(void* map, unsigned int k, int v);
I include foo.h
and I'm good to go.
Now, I wanted to iterate over a map and noticed C++ does that through iterators. I have no experience with C++ and don't know how iterators are implemented.
Can I iterate over a std::map
using a C wrapper? How would these functions definitions look like and how would I use them in a for-loop in my C code?
You won't be able to use iterators directly. You can, of course, do something along the lines of creating/releasing objects and obtain the values somehow. It isn't going to be efficient, though. It would look something like this:
This particular approach does reduce the flexibility coming with iterators a bit (e.g., it doesn't support subranges) but these could be supported at different costs. You'd use this iterator approach like this:
It is probably more reasonable to not expose the iterator interface but rather an interface iterating over the sequence, e.g.:
... which would be used as
I haven't tried to compile the code (i.e., it is probably riddled with small typos) but something along those lines should work.