Vote count:
1
So I've read Developing C wrapper API for Object-Oriented C++ code and I like the approach, which I have taken with my library - opaque handles for each corresponding C++ class; avoiding using void*
But now, I'm faced with thinking about 'interfaces', and base classes. For example, I have a class hierarchy of "channel" classes - a base class for a "channel" and derived concrete classes for, for example, serial comms, in-memory buffers, sockets, etc.
So I have:
typedef struct serial_channel serial_channel;
typedef struct socket_channel socket_channel;
typedef struct memory_channel memory_channel;
serial_channel* create_serial_channel();
socket_channel* create_socket_channel();
memory_channel* create_memory_channel();
But I want to be able to pass any one of those into a function to associate it with a 'device' object:
void associate_device_with_channel(device*, channel*);
Easy in C++, since it understands base classes. How do I approach this in the C wrapper library - what type is channel
in C?
The only thing I can think of is that I must resort to void* to represent a base class?
typedef void* channel;
void associate_device_with_channel(device*, channel*);
It works, but would let me pass any pointer?
On the other extreme, I can write a set of functions matching the derived channel classes:
void associate_device_with_serial_channel(device*, serial_channel*);
void associate_device_with_socket_channel(device*, socket_channel*);
void associate_device_with_memory_channel(device*, memory_channel*);
It's very verbose, and if I have to add new channel types, I have to add new functions to the interface as well.
Is there some kind of middle ground I've been missing? - like a single function, but not void*?
Aucun commentaire:
Enregistrer un commentaire