6 ms·
C Object Oriented Programming (2014)
- adraenwan 3y agoHere is a very simple linux driver https://github.com/torvalds/linux/blob/master/drivers/pwm/pwm-clps711x.c https://github.com/torvalds/linux/blob/master/drivers/pwm/pw...
- naitgacem 3y agoExcellent writeup and straight to the point. As the author demonstrated one can get quite a lot of OOP constructs using C primitives. what seems to be impossible to implement (as least to me) was something like interfaces, a way to decouple in a way such that high level functions don't need to know about the low level building blocks.
- skribanto 3y agoYou can approximate it by maintaining some kind of vtable, but it can get messy, especially if you need to implement multiple traits/interfaces.
- pjmlp 3y agoWe used to have books about it, and stuff like COM, SOM, CORBA also support C, which is exactly what you're referring to. Regarding books, here is one from 1993, https://www.mclibre.org/descargar/docs/libros/ooc-ats.pdf https://www.mclibre.org/descargar/docs/libros/ooc-ats.pdf
- vkazanov 3y agoClassic..! I wonder how it feels now, 20 years after reading it for the first time. I remember how revelatory it felt.
- thesuperbigfrog 3y agoLinks to Axel-Tobias Schreiner's books: https://www.cs.rit.edu/~ats/books/ https://www.cs.rit.edu/~ats/books/ "Object-Oriented Programming with ANSI-C" (English): https://www.cs.rit.edu/~ats/books/ooc.pdf https://www.cs.rit.edu/~ats/books/ooc.pdf "Objekt-orientierte Programmierung mit ANSI-C" (German): https://www.cs.rit.edu/~ats/books/ooc_de.pdf https://www.cs.rit.edu/~ats/books/ooc_de.pdf
- miuramxciii 3y agoYes, You can. The entire Linux device interface, to name just one example, if full of interfaces. The way to accomplish this is via pointer to functions, and to have it as an object, have these pointer to functions grouped in a struct. GTK/Glib is notably full of these interfaces too.
- spaceywilly 3y agoYup. In a past job I did a lot of work writing ALSA drivers for custom souncards. The ALSA interface is a good example of this. They provide an API app developers can use to do sound stuff (change the volume, for example). In your sound card driver you provide an implementation of the API to do whatever changing the volume means for your particular hardware (in my case sending an i2c message to a digital potentiometer). https://www.kernel.org/doc/html/v4.14/sound/kernel-api/alsa-driver-api.html https://www.kernel.org/doc/html/v4.14/sound/kernel-api/alsa-...
- bryancoxwell 3y agolibusb is a good reference for this as well, and well documented.
- dboreham 3y agoUm, this is how software was built in the olden days. C++ literally began as "we could write a preprocessor to automate the tricks everyone uses to implement polymorphism in C" (CFront). And prior to that, the same tricks were used in assembly language programming. So this article has recreated the history of OOP, which was to create tooling to better support programming techniques already widely used. It wasn't some religion invented by the priests and sent forth on tablets, although due to humans loving them some cult, it became that eventually.
- dceddia 3y agoOne thing to look at is ffmpeg in its encoders and decoders. At the bottom of the file there's a struct with pointers to functions (among other things). Anything that wants to do decoding can just call init(), decode(), close() on an AVCodec and the internal functions do whatever they need to do. Here's one from h264.c: AVCodec ff_h264_decoder = { .name = "h264", .type = AVMEDIA_TYPE_VIDEO, .init = ff_h264_decode_init, .close = h264_decode_end, .decode = h264_decode_frame, ... more fields ... };
- alex_smart 3y agoWhen you read or write from a FILE in C, do you know or have to care about whether the FILE comes from disk, a pipe, a CD drive, or a device driver or a network mounted drive? What do you think FILE is if not an interface?
- nanolith 3y agoOne advantage to this approach is that there is less compiler magic going on. I use a similar approach, but I prefer using type safe upcasting or model checked downcasting via inline functions or explicit references to base members, instead of direct C style casting. This also makes it easier to develop a uniform resource management strategy with allocator abstraction. Being able to easily switch between tuned bucket, pool, or bump allocation strategies can do wonders for optimization. It's possible to model check that downcasting is done correctly, by adding support for performing type checks at analysis time. In this case, a type variable is added to the base type that can be compared before casting. Since this is an analysis only variable, it can be wrapped in a macro so that it is eliminated during normal compilation. Static assertions checked by the model checker during analysis time may need to be refactored to extract the type information as a proof obligation made by the caller. This technique actually works quite well using open source model checkers like CBMC. Either way, some C OOP is not only useful to provide some optimization knobs, but it's also quite useful for introducing annotations that can help to formally verify C but that don't actually incur any runtime overhead.
- alex_smart 3y agoThe biggest advantage of C-style polymorphism vs, say, C++ is that it actually offers much better encapsulation. Having private methods declared in the header file which is supposed to be the public contract for the class is such an anti-pattern. And the usual solutions offered for this problem are ugly in their own right (*pImpl). I only properly learnt to appreciate the power and beauty of OOP by reading people’s C code.
- o11c 3y agoHmm, I don't have much to disagree with for this link, unlike many things from that site. One minor point - the method implementations should not be `static`, so that you can support further subclassing and reuse the base class implementations. Note that to support both virtual and non-virtual method binding, the dispatcher also needs to be exported (with the same signature). This is already the case in the linked code but a point isn't made of it; it can be tempting to abuse `inline` but remember that is primarily about visibility [1]. It also doesn't mention how to implement `dynamic_cast` (practically mandatory for multimethod-like things), which can be quite tricky, especially in the multiple-inheritance case and/or when you don't know all the subclasses ahead of time and/or when you have classes used in across shared libraries. There are cases where you really do need multiple vtables. Virtual inheritance, despite its uses, is probably a mistake so it's fine that it ignores that. [1]: https://stackoverflow.com/a/51229603/1405588 https://stackoverflow.com/a/51229603/1405588
- rileyphone 3y agoIs there anything you need multimethods for that can't be patched with visitors and other design patterns? They have always seemed to me like a neat feature that are devilishly tricky to implement and difficult to reason about for the average programmer.
- o11c 3y agoYou don't need multimethods per se, but you need something and `dynamic_cast` is usually easiest (and with reasonable restrictions, most efficient). Overloaded operators is a major category of problem here. The "which subclass (if any) is more derived" might be done by the compiler proper, but that still needs to use the cast internally. And of course if you ignore operator overloading, you're just pulling a Java and mandating extra verbosity; the user's problem still has to be solved the exact same way. (most other use cases for multimethods I don't find compelling)
- nemetroid 3y agoSuccessful dynamic_casts are fast. But failing dynamic_casts usually involve at least one strcmp and are extremely expensive. https://gcc.gnu.org/legacy-ml/gcc-patches/2009-07/msg01239.html https://gcc.gnu.org/legacy-ml/gcc-patches/2009-07/msg01239.h...
- senderista 3y agoI had the great fortune to work briefly on the MS Word codebase, and I remember some ancient C code that manually implemented vtables. Probably not uncommon for that era.
- pjmlp 3y agoMost likely OLE related.
- itsboring 3y agoKeep going and you eventually arrive at GLib
- andai 3y ago>Object oriented programming, polymorphism in particular, is essential to nearly any large, complex software system. Without it, decoupling different system components is difficult. (Update in 2017: I no longer agree with this statement.) The author doesn't seem to elaborate on this. I was taught OOP in university and then promptly learned that it's frowned upon in performance sensitive code, which is my main interest in programming. (And that it apparently doesn't even achieve its stated goal of making the code easier to understand -- I've certainly had the experience of wading through a deep inheritance hierarchy (or call stack) looking for the "actual code that actually runs"...) I'd love to hear an elaboration on that idea (OOP is essential for decoupling components) and its counterargument (decoupling can apparently be done just fine without OOP?).
- tus666 3y ago> is essential to nearly any large, complex software system > in performance sensitive code Those two things are not the same.
- billforsternz 3y agoThe question you're responding too already makes it clear those things are quite different, perhaps even orthogonal.
- randomdata 3y agoCentral to OOP is message passing between objects. Few languages utilize message passing, so it seems you can decouple components without OOP just fine.
- andai 3y ago>Few languages utilize message passing Yet most of them call themselves object-oriented! I'm reminded of the Alan Kay quote, "I invented the term object-oriented, and I can tell you that C++ wasn't what I had in mind."
- 3y ago
- 1bent 3y agoOne domain that a little OO seems to map to without too much pain is GUI libraries. The first OO-flavoured API I ever used was Sunview, the early GUI I used on Sun-3 workstations with SunOS. It was a beautiful API; I was never tempted to mess with the verbose, complex "Intrinsics-based" toolkits that followed it. It carried on with xview; that's what I'd try if I wanted to write a GUI in C today.