Handmade Network»Forums
1 posts
Polymorphism with Go-like interfaces in C?
Edited by escalioth on

I'm writing a ray tracer based on Peter Shirley's "Ray tracing in one weekend" book. The code in the book is written in C++ and he used virtual functions (ugh) to delegate the task of computing if an object in the scene has been hit by a ray to the object themselves. I rewrote it in Go, and the interfaces there are so much better to work with, because of the real separation between interface and implementation. Now I'd like to rewrite it in C, but how should I deal with polymorphism? I ask here because maybe someone came up with a simple solution which works in general, when you have to implement polymorphism in C.

161 posts / 1 project
Polymorphism with Go-like interfaces in C?
Edited by Dawoodoz on

You can have structs of function pointers replacing the virtual calls. Ideal for the strategy pattern, because you can have multiple behaviors in the same object, as opposed to allocating a new object for each set of functions. If the classes need different variables and you don't want to reuse them, you can use a pointer to an arbitrarily sized buffer and allocate it on construction. Reusing variables will however allow you to allocate fixed size memory on the stack and change functions individually at runtime without resetting the object's state, which is not possible in strict object orientation where you only store a fixed virtual function table per class. The CPython reference implementation relies heavily on structs of function pointers for classes in C.


37 posts
Polymorphism with Go-like interfaces in C?

The core insight in the way Go does interfaces is that you pass around pairs of pointers like

struct interface { void *value; void *methods; };

instead of putting the methods pointer on the object. This means to do polymorphism you just need a way to figure out if there is an appropriate table of methods for the value type you have and you stuff it in there. In C... keep it simple, it's not going to be as ergonomic as go

Here's the email about Haskell that gets passed around as the mythic realization of the potential of this idea, if you're curious https://homepages.inf.ed.ac.uk/wadler/papers/class-letter/class-letter.txt

For a ray tracer, though, you might not need polymorphism at all.

Now, how about several spheres? While it is tempting to have an array of spheres,

Indeed it is, Peter, indeed it is