Skip to content

Instantly share code, notes, and snippets.

@milesrout
Last active June 12, 2016 11:53
Show Gist options
  • Save milesrout/4abbe52d7a7487aad4ba1d6265b9e534 to your computer and use it in GitHub Desktop.
Save milesrout/4abbe52d7a7487aad4ba1d6265b9e534 to your computer and use it in GitHub Desktop.
Chalice Examples
int add(int x, int y)
{
        return x + y;
}

int main()
{
        assert_eq(3, add(1, 2));
}

Chalice will be able to read C headers directly, so you do not have to write bindings.

import libc/stdio;

You can then use the standard C std i/o functions directly:

int main()
{
        int n;
        printf(c"What is your age? ");
        scanf(c"%d", &n);
        printf(c"%d\n", 5);
}

However there are also some more idiomatic bindings for Chalice:

import io;

int main()
{
        int err, n;
    
        ask(&err, "What is your age?", &n);
        print(&err, "You are %d years old.\n", n);
}

Chalice's strings are rather different from strings in C. Chalice's strings are length-prefixed. You can construct C strings in a couple of ways.

You can construct C strings using c"" string literals.

char* str1 = c"Hello, world!";

You can construct C strings from Chalice strings using the to_cstr function:

string* str2 = "Hello, world!";
char* str2 = to_cstr(str2);

Chalice arrays are also rather different to C-style arrays. Chalice arrays are not implicitly convertible into pointers. Instead, Chalice arrays behave like proper object/value types.

float sum(float* first, last)
{
        float total = 0;
        while (first != last)
                total += *first++;
        return total;
}

int main()
{
        float[] x = { 1.0f, 2.0f, 3.0f, 4.0f, 5.0f };
        float total = sum(&x[0], &x[last]);
        print("The total is %d.\n", total);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment