Hacker News new | ask | show | jobs
by rhodysurf 2456 days ago
You can use any c libraries networking or socket implementations in zig but I think thats as far as it goes at the moment.
2 comments

zig's C-interoperability is second to none and using libcurl works great for networking.

example: https://github.com/donpdonp/zootdeck/blob/master/src/net.zig

Nim and d both have comparable interop, and nim even works with c++.
To be fair, Zig's C interoperability appears to be inspired or borrowed from Swift's little known secret called the ClangImporter.
Can you though? I cant get cURL to work:

https://github.com/ziglang/zig/issues/988

After a few minutes of trial and error (mostly around convincing Zig's type checker that various things are indeed enum members, and fixing cases where the C version outright ignores return values), I was able to produce a working example:

    // curl-test.zig
    // Direct hand-translation from curl's simple.c example
    usingnamespace @cImport({
        @cInclude("stdio.h");
        @cInclude("curl/curl.h");
    });
    
    pub fn main() anyerror!void {
        var curl = curl_easy_init();
        var res: CURLcode = undefined;
    
        if(curl != null) {
            _ = curl_easy_setopt(curl, CURLoption.CURLOPT_URL,
                                 c"https://example.com");
            _ = curl_easy_setopt(curl, CURLoption.CURLOPT_FOLLOWLOCATION, c_long(1));
    
            res = curl_easy_perform(curl);
        
            if(res != CURLcode.CURLE_OK) {
                _ = fprintf(stderr, c"curl_easy_perform() failed: %s\n",
                            curl_easy_strerror(res));
            }
        
            curl_easy_cleanup(curl);
        }
    }
Buildable with "zig build-exe curl-test.zig --library c --library curl" (I have to add "-isystem /usr/include --library-path /usr/lib64" to the end of that on Slackware64 14.2; YMMV). Should produce a runnable "curl-test" (or "curl-test.exe") binary executable in the current dir.