C for C ++ library - what about inheritance?

So, I read Developing a wrapper API for object-oriented C ++ code , and I like the approach I used in my library - opaque handles for each corresponding C ++ class; avoiding usevoid*

But now I came across the thought of “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 communications, buffers in memory, sockets, etc.

So, I have a:

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 of them to a function in order to associate it with the 'device' object:

void associate_device_with_channel(device*, channel*);

++, . C - channel C?

, , , void * ?

typedef void* channel;
void associate_device_with_channel(device*, channel*);

, ?

, , :

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*);

, , .

- , ? - , void *?

+4
3

. (, ), ( void*), C .

, , serial_channel* channel*, - channel. C- numfuncs*numderivedclasses channel - .

void* . , C... , , .

+3

-, :

typedef void base_class;
struct base_class_impl
{
    // base class member variables go here
}
struct derived_class
{
    // base class must come first in the derived struct
    struct base_class_impl base;
    // derived class member variables go here
}

base_class :

int base_class_get_count(base_class *b);

:

int base_class_get_count(base_class *b)
{
    struct base_class *base = (struct base_class *)b;
    // Operate on the object now
}

base_class_get_count() . , - , , API- (, base_class_get_count) .

+2

GCC Clang ( , C, Visual Studio), - __transparent_union__, , . , union __transparent_union__, , .

union associable_channel
{
    channel* a;
    serial_channel* b;
    socket_channel* c;
    memory_channel* d; 
} __attribute__((__transparent_union__));

void associate_device_with_channel(union associable_channel chan);

serial_channel* serial;
socket_channel* socket;
memory_channel* mem;
associate_device_with_channel(serial);
associate_device_with_channel(socket);
associate_device_with_channel(mem);
+1

Source: https://habr.com/ru/post/1529999/


All Articles