C3: C Interop

In this post we’re going to look at a simple example of how to create a static C library and use it from C3.

C library #

Create mylib.c

typedef struct Point Point;

struct Point {
    int x;
    int y;
};

void point_add(Point* a, Point* b, Point* c)
{
    c->x = a->x + b->x;
    c->y = a->y + b->y;
}

Now, let’s create our static library.

gcc -c mylib.c
ar rcs libmylib.a mylib.o

Calling from C3 #

Create main.c3

import std;

struct Point
{
	int x;
	int y;
}

extern fn void point_add(Point* a, Point* b, Point* dest);

fn int main()
{
	Point a = { 1, 1 };
	Point b = { 1, 2 };

	Point c = {};

	point_add(&a, &b, &c);

	io::printfn("x: %d, y: %d", c.x, c.y);

	return 0;
}

All we had to do was define the appropriate struct and a function declaration with the extern keyword.

Now, compile the C3 source file and link our C library.

c3c compile main.c3 -L . -l mylib
./main
x: 2, y: 3

It would be nice to put this in a module with a wrapper so that we could call point::add instead. I’ll cover this in a later post.

Resources #

c3-lang.org: cinterop