英文:
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 <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
}
答案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 <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)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论