我正在尝试重新打包一些与现有C库集成的go代码。
以下是完美的工作方式。
档案1:
package avcodec
type Codec C.struct_AVCodec档案2:
package avformat
//#cgo pkg-config: libavformat libavcodec
//#include <libavformat/avformat.h>
//#include <libavcodec/avcodec.h>
import "C"
import (
"unsafe"
)
type Codec C.struct_AVCodec
func (s *FormatContext) AvFormatGetVideoCodec() *Codec {
result := C.av_format_get_video_codec((*C.struct_AVFormatContext)(s))
return (*Codec)(result) // <- This works. Codec is defined in this package.
}如果我试图引用或者将Codec从文件2移到单独的包中(例如。文件1)我得到了错误:
不能将(func文字)((*C.struct_AVFormatContext)(S))(类型*C.struct_AVCodec)转换为类型*Codec
例如,这失败了:
package avformat
//#cgo pkg-config: libavformat libavcodec
//#include <libavformat/avformat.h>
//#include <libavcodec/avcodec.h>
import "C"
import (
"avcodec"
"unsafe"
)
func (s *FormatContext) AvFormatGetVideoCodec() *avcodec.Codec {
result := C.av_format_get_video_codec((*C.struct_AVFormatContext)(s))
return (*avcodec.Codec)(result) // <- This fails. Codec defined in avcodec.
}这也失败了:
package avformat
//#cgo pkg-config: libavformat libavcodec
//#include <libavformat/avformat.h>
//#include <libavcodec/avcodec.h>
import "C"
import (
"avcodec"
"unsafe"
)
type Codec avcodec.Codec
func (s *FormatContext) AvFormatGetVideoCodec() *Codec {
result := C.av_format_get_video_codec((*C.struct_AVFormatContext)(s))
return (*Codec)(result) // <- This also fails. Codec is based on avcodec.Codec.
}我想:
Codec包中定义的avcodec类型。提前谢谢。
发布于 2017-04-03 20:42:49
这是由于Go如何表示类型而导致的失败。
例如,考虑到:
//Ex1
package avformat
//.. deleted for simplicity
type Codec C.struct_AVCodec...and
//Ex2
package avcode
//.. deleted for simplicity
type Codec C.struct_AVCodec在上面的代码中,ex1中的C.struct_AVCodec与ex2中的C.struct_AVCodec不同,尽管它们在词汇上是相同的。
具体来说,ex1中的完全限定类型是avformat._Ctype_struct_AVCodec,而ex2是avcodec._Ctype_struct_AVCodec。
这解释了为什么package avformat中试图将任何东西从外部类型(在本例中是从package avcodec)转换到本地C.struct_AVCodec的函数失败的原因。
解决方案
为了使这个工作正常,我依赖于类型断言。
package avformat
func (s *FormatContext) AvformatNewStream(c avcodec.ICodec) *Stream {
v, _ := c.(*C.struct_AVCodec)
return (*Stream)(C.avformat_new_stream((*C.struct_AVFormatContext)(s), (*C.struct_AVCodec)(v)))
}...and
package avcodec
type ICodec interface{}https://stackoverflow.com/questions/43192754
复制相似问题