#Should I use a binding instead of translated C?
1 messages · Page 1 of 1 (latest)
translate-c is incomplete and won't work well for a lot of C code
It also won't work for C++ code, obviously
Sorry i need some clarification
And even for the code it supposedly should support, there's occasionally bugs that means it won't work, or won't work correctly
There's also not really many advantages to using translate-c over just compiling the C code and binding to it. The only one I can think of is compilation speed, since the Zig compiler is often considerably faster than clang, but that's only really a one-time cost due to Zig's caching
Are @cImport and translate-c pretty much the same thing?
Yes, cimport internally runs translate-c
It generates a small C file based on the expression passed to @cImport, then literally just calls zig translate-c on it and imports that
Alright I might have some more questions. I'll be back later. Thanks for the information so far.
@stuck orchid Hi are you still there?
hi
I'd like to write my own bindings to get some experience. How would I do that?
You can either define all the extern fns etc yourself, manually translating from the C headers, or you can simply @cImport the headers and then write bindings around those
For the second option, normally you'd create opaques or extern structs for each of the relevant C types, and convert between them and the C versions using casts
Making those wrappers allows you to put instance functions on them, which makes for much nicer Zig APIs
neat
What would an extern function look like.
ah alright something like extern fn my_func(a: i32, b: i32) i32;
but it would have the C calling convention?
No nevermind I am dumb.
You can specify the call convention with callConv, examples can be found here
https://ziglang.org/documentation/master/#Functions
What about header-only libs?
You should still be able to compile those right?
header-only libs as in the ones that use the #define LIB_FOO_IMPLEMENTATION model have to have the API's functions defined by including the header file in a source file after the aforementioned macro def, which you compile; from there, you can either use translate-c, or manually translate the bindings yourself
header-only libs as in ones that are comprised of a bunch of static functions defined inline are unfriendly to translate-c, so kind of stuck between a rock and a hard place there