Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>If you can, use struct "interfaces":</p> <pre><code>struct Device { int (*read_temp)(int*, Device*); } *dev; </code></pre> <p>call it:</p> <pre><code>dev-&gt;read_temp(&amp;ret, dev); </code></pre> <p>If you need additional arguments, pack them inside Device</p> <pre><code>struct COMDevice { struct Device d; int port_nr; }; </code></pre> <p>and when you use this, just downcast.</p> <p>Then, you'll create functions for your devices:</p> <pre><code>int foo_read_temp(int* ret, struct Device*) { *ret = 100; return 0; } int com_device_read_temp(int* ret, struct Device* dev) { struct COMDevice* cdev = (struct COMDevice*)dev; /* could be made as a macro */ ... communicate with device on com port cdev-&gt;port_nr ... *ret = ... what you got ... return error; } </code></pre> <p>and create the devices like this:</p> <pre><code>Device* foo_device= { .read_temp = foo_read_temp }; COMDevice* com_device_1= { .d = { .read_temp = com_read_temp }, .port_nr = 0x3e8 }; COMDevice* com_device_1= { .d = { .read_temp = com_read_temp }, .port_nr = 0x3f8 }; </code></pre> <p>You'll pass the Device structure around to function that need to read the temperature.</p> <p>This (or something similar) is used in the Linux kernel, exceptthat they don't put the function pointers inside the structs, but create a special static struct for it and stor pointer to this struct inside the Device struct. This is almost exactly how object oriented lingages like C++ implement polymorphism.</p> <p>If you put the functions in a separate compilation unit, including the Device struct that refer to them, you can still save space and leave them out while linking.</p> <p>If you need different types of arguments, or fewer arguments, just forget it. This means you cannot design a common interface (in any sense) for things you want to change, but without a common interface, no changeable implementation is possible. You can use compile-time polymorphism (eg. typedefs &amp; separate compilation units for different implementations, one of which would be linked in your binary), but it still has to be at least source-compatible, that is, be called in the same way.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload