Object Oriented C : Interfaces

By Sagar

In this article I’m going to demonstrate an approach which allows one to use interfaces in C code.

Let’s say we want an interface NetworkClient in our codebase, which provides the following methods:

  • char* getURL()
  • JSONObject* getParams()
  • void processResponse(char*)
  • void handleError(Error)’

How do we implement this in C?

Let’s create a struct NetworkClient which represents our interface:

We’ll add a method to our struct-class which generates the interface and returns it:

Now we can pass the struct created by  Client_getNetworkClient to code that expects an object with NetworkClient interface:

This is how we consume the interface:

As a matter of fact, this is how  trait objects are implemented in rust-lang, as a collection of function pointers coupled with an object on which those functions should be called.

 See you later.