🚀 go-pugleaf

RetroBBS NetNews Server

Inspired by RockSolid Light RIP Retro Guy

Article View: comp.lang.c
Article #1550

Re: Inversion-of-control and dependency-injection in C

#1550
From: fir
Date: Sun, 15 Nov 2026 11:03
414 lines
12965 bytes
Tristan Wibberley pisze:
> On 13/11/2026 22:50, Ross Finlayson wrote:
> 
>> So, here's one. Say you got a server process for sockets of the
>> connection-oriented or datagram-wise or association-oriented like
>> TCP, UDP, or SCTP, and it manages the connecting and the sending and
>> receiving about a million of those and is sort of fixed-size and
>> stable in a usual runtime. So, how do you design the interface,
>> about stuff like the state-machine of _protocols_, all about
>> _protocols_, in the application-layer and above, say, for example
>> the incremental-parsing and the state-machine of the protocol
>> and sub-protocols and upgrade-protocols and the like, what sort
>> of abstraction with suitable-defaults and reasonable-opinions
>> makes for having any sort protocol as a composable library.
> 
> 
> For anyone who either doesn't understand that text or doesn't get how
> valuable it is just as a question unanswered: please know that it is super.
> 
> To Ross: nobody using Usenet is going to be able to give an adequate
> answer. Maybe a dozen people on the planet can give such an answer and
> maybe each of a dozen teams of academics could do it with several years
> work.
> 
ai may answer it in about 10 seconds:


C does not really need a special component model for this. Most of what 
you describe can be done with a fairly small number of ordinary C 
mechanisms, provided that the boundaries between them are made explicit.

The important distinction, in my opinion, is between a **source 
module**, a **runtime module**, and an **interface**.

A `.c` file is a compilation unit, not necessarily a runtime component. 
Several `.c` files may form one library or runtime component, while one 
`.c` file may contain several logically unrelated things. The actual 
runtime boundary is usually represented by an API and, if necessary, by 
a table of function pointers.

For example, instead of making an object hierarchy, one can simply define:

```c
struct renderer {
     void (*draw)(struct renderer *, const void *);
     void (*clear)(struct renderer *);
     void (*destroy)(struct renderer *);
     void *context;
};
```

An implementation constructs such a structure:

```c
struct renderer *CreateSoftwareRenderer(void);
struct renderer *CreateOpenGLRenderer(void);
```

The rest of the program only knows about `struct renderer` and its 
contract. It does not need to know which implementation was constructed.

That already gives you a fairly direct form of dependency injection:

```c
struct renderer *renderer = CreateSoftwareRenderer();
game.renderer = renderer;
```

or, even more explicitly:

```c
game.renderer.draw = SoftwareDraw;
game.renderer.clear = SoftwareClear;
game.renderer.destroy = SoftwareDestroy;
game.renderer.context = &software_state;
```

There is no fundamental requirement that the dependency be discovered 
globally. It can simply be passed to the code which needs it.

In fact, I would say that **passing dependencies explicitly is one of 
the most natural forms of dependency injection in C**.

The same technique works without function pointers when the dependency 
is data rather than behavior. For example:

```c
struct allocator {
     void *(*alloc)(struct allocator *, size_t);
     void (*free)(struct allocator *, void *);
     void *context;
};
```

Then a subsystem can receive an allocator without knowing whether it 
ultimately uses `malloc`, a pool, an arena, a debug allocator, or 
something supplied by a test harness.

This is also where ownership belongs. The interface should state things 
such as:

```c
void *ResourceCreate(...);
void ResourceDestroy(void *);
```

and document who owns the returned resource and when `Destroy` must be 
called. C has no language-level ownership system, so this is part of the 
API contract rather than something the compiler enforces.

For test-time versus run-time implementations, I would normally avoid 
conditional compilation inside the actual application code.

Instead of:

```c
#ifdef TEST
     ...
#else
     ...
#endif
```

I prefer:

```c
struct filesystem {
     int (*read)(struct filesystem *, ...);
     int (*write)(struct filesystem *, ...);
     void *context;
};
```

and then construct either:

```c
CreateRealFilesystem(...)
```

or:

```c
CreateTestFilesystem(...)
```

The application remains identical.

Conditional compilation is still useful when the implementations 
themselves genuinely require different platform facilities:

```c
#ifdef _WIN32
     ...
#elif defined(__linux__)
     ...
#endif
```

or when selecting which implementation is compiled into a particular target.

That distinction is useful:

**conditional compilation chooses code; dependency injection chooses 
behavior.**

Build systems then decide which source files participate in a target.

For example, conceptually:

```text
game
     game.c
     renderer.c
     renderer_software.c

game_test
     game.c
     renderer.c
     renderer_test.c
```

Both targets can satisfy the same interface, while linking different 
implementations.

With static linking, the boundary is mostly a linker boundary. With 
dynamic linking, it can additionally become an operating-system module 
boundary (`DLL`, `.so`, etc.). The C interface does not fundamentally 
change.

A DLL can export something as simple as:

```c
struct renderer *CreateRenderer(void);
```

and the host can obtain that symbol dynamically. The ABI then becomes 
part of the contract, which is where things such as calling conventions, 
structure layout, symbol visibility, versioning, and ownership across 
module boundaries become important.

There is also no particular reason why every dependency needs to be 
represented by a huge nested structure of function pointers. That can 
become its own form of accidental object-oriented programming.

Often this is enough:

```c
struct game {
     struct renderer *renderer;
     struct filesystem *filesystem;
     struct clock *clock;
};
```

and each interface contains only the operations that actually belong to it.

This gives you something resembling a manually constructed object graph:

```text
                  game
               /   |    \
              /    |     \
        renderer filesystem clock
           |          |       |
       software     test    fake
```

The graph is constructed at startup. The game does not construct its own 
concrete dependencies; somebody outside it does.

That is essentially the interesting part of inversion of control in C.

The phrase "IoC" can sound much more exotic than the mechanism actually 
is. At the simplest level it means:

 > Instead of this subsystem deciding what implementation it will use, 
somebody else gives it the implementation.

Function pointers are one way of doing that. Plain function arguments 
are another, and often the better one.

For example, a function such as:

```c
void Simulate(struct simulation *s,
               float (*random)(void),
               void (*log)(const char *));
```

is already dependency injection. No component framework is required.

Likewise, a callback is already a small form of inversion of control:

```c
void EnumerateFiles(const char *path,
                     void (*callback)(const char *name, void *context),
                     void *context);
```

The library controls the enumeration and calls code supplied by the caller.

So I would not start by designing "components". I would start by 
identifying **contracts**.

For each subsystem ask:

1. What does the caller need to know?
2. What must remain private?
3. Who owns the resources?
4. Which behavior needs to be replaceable?
5. Does it actually need runtime replacement, or is link-time selection 
enough?
6. Does the boundary need to cross a shared-library/ABI boundary?

Then choose the simplest mechanism:

```text
ordinary function call
         ↓
function parameter / callback
         ↓
context pointer
         ↓
struct containing function pointers
         ↓
separate static library
         ↓
dynamic library / plugin
         ↓
full component framework
```

I would only move down that list when the simpler mechanism stops being 
sufficient.

In particular, I would be rather suspicious of reproducing COM in C 
merely because COM solves a problem that C does not have. A table of 
function pointers plus a context pointer is already surprisingly close 
to the essential machinery of an object interface:

```c
struct interface {
     void *context;

     int  (*open)(void *context);
     int  (*read)(void *context, void *buffer, size_t size);
     void (*close)(void *context);
};
```

The context provides instance state, the function pointers provide 
polymorphic behavior, and the header defines the contract.

Multiple interfaces are simply multiple such tables, rather than 
multiple inheritance:

```c
struct device {
     struct input_interface input;
     struct output_interface output;
     struct diagnostic_interface diagnostic;
};
```

If a component has to support querying for optional interfaces, then 
something resembling `QueryInterface()` can certainly be implemented. 
But again, that is a convention built on ordinary C rather than a 
language feature.

There is one more important point about "modularity": **the header is 
not necessarily the interface**.

A good C module often has:

```c
foo.h
foo.c
```

where `foo.h` exposes the public contract and `foo.c` contains private 
structures and implementation details.

For example:

```c
/* foo.h */

struct foo;

struct foo *FooCreate(void);
void FooDestroy(struct foo *);
int FooDoSomething(struct foo *);
```

while `struct foo` itself is private.

That gives you opaque state without needing classes:

```c
struct foo {
     int private_state;
     ...
};
```

The caller can hold a `struct foo *` but cannot depend on its 
representation.

This is often more valuable for long-term modularity than adding another 
layer of function-pointer indirection.

So, in short, C has most of the machinery being described here, but it 
is deliberately not packaged into one language-level object/component 
system.

You have:

```text
.h/.c
     → source/module boundaries

opaque structs
     → encapsulation

function pointers + context
     → interfaces / polymorphism

callbacks
     → inversion of control

explicit parameters
     → dependency injection

constructors/factory functions
     → choosing implementations

static libraries
     → link-time composition

shared libraries
     → runtime composition

build configuration
     → selecting implementations

explicit create/destroy contracts
     → resource ownership
```

The interesting part is not that C lacks these abstractions. It is that 
**C lets you assemble them yourself**, which means the programmer also 
has to decide where the abstraction is actually justified.

And that last part is both C's freedom and C's trap.
Technical Details
Message-ID: <11dc3k2$2mlue$1@dont-email.me>
Path: mbox-mo1.pugleaf.net!news-lax.pugleaf.net!srl.newsdeef.eu!newsfeed.bofh.team!eternal-september.org!feeder.eternal-september.org!nntp.eternal-september.org!.POSTED!not-for-mail
References: <yQOdnQ-qnKiiZ2j3nZ2dnZfqn_udnZ2d@giganews.com> <11d56gl$3ud5q$1@dont-email.me> <11d6vjp$qhu8$1@raubtier-asyl.eternal-september.org> <dsednTD-Fblclmr3nZ2dnZfqnPWdnZ2d@giganews.com> <11d738r$ru7a$1@dont-email.me> <11d75i7$spj0$1@dont-email.me> <11d7c8k$173nk$1@dont-email.me> <11d7fbv$1839o$2@dont-email.me> <nrecnTdvuvbACWr3nZ2dnZfqn_adnZ2d@giganews.com> <11dc1cj$2lp70$1@dont-email.me>

Show Full Headers
Complete Article Headers
Path: mbox-mo1.pugleaf.net!news-lax.pugleaf.net!srl.newsdeef.eu!newsfeed.bofh.team!eternal-september.org!feeder.eternal-september.org!nntp.eternal-september.org!.POSTED!not-for-mail
From: fir <profesor.fir@gmail.com>
Newsgroups: comp.lang.c
Subject: Re: Inversion-of-control and dependency-injection in C
Date: Sun, 15 Nov 2026 12:03:54 +0100
Organization: A noiseless patient Spider
Lines: 414
Message-ID: <11dc3k2$2mlue$1@dont-email.me>
References: <yQOdnQ-qnKiiZ2j3nZ2dnZfqn_udnZ2d@giganews.com>
 <11d56gl$3ud5q$1@dont-email.me>
 <11d6vjp$qhu8$1@raubtier-asyl.eternal-september.org>
 <dsednTD-Fblclmr3nZ2dnZfqnPWdnZ2d@giganews.com>
 <11d738r$ru7a$1@dont-email.me> <11d75i7$spj0$1@dont-email.me>
 <11d7c8k$173nk$1@dont-email.me> <11d7fbv$1839o$2@dont-email.me>
 <nrecnTdvuvbACWr3nZ2dnZfqn_adnZ2d@giganews.com>
 <11dc1cj$2lp70$1@dont-email.me>
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8; format=flowed
Content-Transfer-Encoding: 8bit
Injection-Date: Sun, 15 Nov 2026 11:04:35 +0000 (UTC)
Injection-Info: dont-email.me;
	logging-data="2840526"; mail-complaints-to="abuse@eternal-september.org";	posting-account="U2FsdGVkX18cRbNdBM6UIgrlcp7dShpWsA+oHgHZca8="; posting-host="81b52da96affb9ab2053deab2a558ee5"
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:140.0) Gecko/20100101
 Firefox/140.0 SeaMonkey/2.53.24
Cancel-Lock: sha1:KWdqwyE2XEzdma14+iDhWRsPlI8= sha256:n5kIKzzxgjUn1SmxKzMg1jNeNwj0L4n8xyW79PIcjUs=
	sha1:/WlOca3ZPGn3gwNmzVVWmbV5nHY= sha256:r7HHA2yBPLTtY11SI/0kKvVWuZc1fPxNqg4mC77Kwic=
In-Reply-To: <11dc1cj$2lp70$1@dont-email.me>