How can I wrap zlib in golang?

I tried to fix the slowest zip implementation of golang by calling c zlib from golang using cgo

but i get the error

error: "deflateInit" uneclared (use in this function first)

deflateInit is defined in zlib.h

Am I missing something? thanks for any hints.

package main

/*
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <assert.h>
#include "zlib.h"
*/
import "C"

import (
    "fmt"
)

func main() {
    fmt.Println("hmmm....")
    fmt.Println(int(C.random()))
    var strm C.struct_z_stream
    fmt.Println(strm)
    ret := C.deflateInit(&strm, 5) // trouble here
}

      

+3


source to share


1 answer


Here is a fixed version of your code. Note #cgo LDFLAGS: -lz

for linking with the zlib library and with a little C function myDeflateInit

which is linked to being deflateInit

a macro, not a function. Notice also the change in definition strm

.

Macros

C is pretty annoying to deal with Go unfortunately - I couldn't think of a better way than a little C shim function.



package main

/*
#cgo LDFLAGS: -lz
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <assert.h>
#include "zlib.h"

int myDeflateInit(z_streamp s, int n) {
     return deflateInit(s, n);
}
*/
import "C"

import (
    "fmt"
)

func main() {
    fmt.Println("hmmm....")
    fmt.Println(int(C.random()))
    var strm C.z_stream
    fmt.Println(strm)
    ret := C.myDeflateInit(&strm, 5)
    fmt.Println(ret)
}

      

+6


source







All Articles