如何在Golang中使用zlib进行封装?

huangapple go评论69阅读模式
英文:

how can I wrap zlib in golang?

问题

我试图通过使用cgo从golang调用c zlib来修复golang最慢的zip实现,但是我遇到了一个错误。

错误:'deflateInit'在此函数中未声明(第一次使用)

deflateInit在zlib.h中定义。

我是否漏掉了什么?谢谢任何提示。

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) // 这里有问题
}
英文:

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

but I get an error

error: 'deflateInit' undeclared (first use in this function)

deflateInit is defined in zlib.h

Am I missing something? thanks for any hints.

package main

/*
#include &lt;stdlib.h&gt;
#include &lt;stdio.h&gt;
#include &lt;string.h&gt;
#include &lt;assert.h&gt;
#include &quot;zlib.h&quot;
*/
import &quot;C&quot;

import (
	&quot;fmt&quot;
)

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

答案1

得分: 7

这是您代码的修复版本。请注意#cgo LDFLAGS: -lz用于链接zlib库以及小的C函数myDeflateInit,该函数处理了deflateInit是宏而不是函数的情况。还请注意strm定义的变化。

很不幸,从Go中处理C宏是相当烦人的 - 我想不出比一个小的C shim函数更好的方法。

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)
}
英文:

Here is a fixed version of your code. Note the #cgo LDFLAGS: -lz to link with the zlib library and the little C function myDeflateInit which deals with the fact that deflateInit is a macro rather than a function. Note also the change in definition of strm.

C macros are rather irritating to deal with from Go unfortunately - I couldn't think of a better way than a small C shim function.

package main

/*
#cgo LDFLAGS: -lz
#include &lt;stdlib.h&gt;
#include &lt;stdio.h&gt;
#include &lt;string.h&gt;
#include &lt;assert.h&gt;
#include &quot;zlib.h&quot;

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

import (
	&quot;fmt&quot;
)

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

huangapple
  • 本文由 发表于 2013年2月4日 19:56:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/14686256.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定