Unexpected Memory Values When Using C Bindings in Mojo

Unfortunately, the ABI of C is horrifically complicated (and extremely target specific) when it comes to passing/returning structs around by-value. Mojo does not make an attempt to know these rules. To address this, please take and return pointers, e.g. write your C code like this:

void init_point2(int x, int y, Point *result) {
    result->x = x;
    result->y = y;
}

If you’re interested in the archane details, check out the “Platform specific abi” (aka “PSABI”) for the architectures you’re interested in, e.g. x86-64 is here:

You can see the crazy rules in “3.2.3 Parameter Passing”. At some point, Mojo is likely to integrate with Clang so we can have really beautiful C/C++ FFI (like Swift does) but this is not on the roadmap yet.

-Chris

5 Likes