首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >重新打包C类型会导致Go中的类型转换错误

重新打包C类型会导致Go中的类型转换错误
EN

Stack Overflow用户
提问于 2017-04-03 19:27:00
回答 1查看 122关注 0票数 3

我正在尝试重新打包一些与现有C库集成的go代码。

以下是完美的工作方式。

档案1:

代码语言:javascript
复制
package avcodec

type Codec C.struct_AVCodec

档案2:

代码语言:javascript
复制
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

例如,这失败了:

代码语言:javascript
复制
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.
}

这也失败了:

代码语言:javascript
复制
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.
}

我想:

  1. 理解失败的原因,并且
  2. 确定如何更改打包,以便函数使用在Codec包中定义的avcodec类型。

提前谢谢。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-04-03 20:42:49

这是由于Go如何表示类型而导致的失败。

例如,考虑到:

代码语言:javascript
复制
//Ex1
package avformat 
//.. deleted for simplicity

type Codec C.struct_AVCodec

...and

代码语言:javascript
复制
//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的函数失败的原因。

解决方案

为了使这个工作正常,我依赖于类型断言。

代码语言:javascript
复制
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

代码语言:javascript
复制
package avcodec

type ICodec interface{}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43192754

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档