快速访问C变量 [英] Access C variable in swift
问题描述
我试图访问在 .h 文件中声明的状态变量,但编译器说该变量不存在.我需要在我的桥接头文件中添加任何东西吗?
I'm trying to access a state variable declare in .h file but the compiler said the variable doesn't exist. Do I need to add anything in my bridging header file ?
在我的 swift 文件中,我无法访问 dstate 或 cstate
In my swift file I can't access dstate or cstate
编译器在 g722_coder_init(&dstate)
行上说Use of unresolved identifier 'dstate'".
The compiler says "Use of unresolved identifier 'dstate'" on the line g722_coder_init(&dstate)
.
头文件
#ifdef __cplusplus
extern "C" {
#endif
extern struct g722_dstate dstate;
extern struct g722_cstate cstate;
int g722_coder_init ( struct g722_cstate *s );
int g722_encode(short *data, unsigned char *outdata,int len, struct g722_cstate *s );
int g722_decoder_init ( struct g722_dstate *s);
int g722_decode(unsigned char *decdata, short *pcmout, int len, struct g722_dstate *s );
#ifdef __cplusplus
}
#endif
桥接标题
#import "g722_codec.h"
推荐答案
问题在于struct g722_dstate
是一个不完整类型",并且 Swift 不能导入不完整类型的变量,只能导入变量指针指向一个不完整的类型(那些被导入如OpaquePointer
).
The problem is that struct g722_dstate
is an "incomplete type",
and Swift cannot import variables of an incomplete type, only variables
which are pointers to an incomplete type (and those are imported
as OpaquePointer
).
将完整的结构定义添加到导入的头文件中成为最简单的解决方案.
Adding the complete struct definition to the imported header file would be the easiest solution.
如果这是不可能的,那么一种解决方法是添加
If that is not possible then one workaround would be to add
#import "g722_codec.h"
static struct g722_dstate * __nonnull dstatePtr = &dstate;
到桥接头文件,该文件定义了一个包含不透明"dstate
变量的地址.这是导入到 Swift 为
to the bridging header file, which defines a variable containing the
address of the "opaque" dstate
variable. This is imported to Swift as
var dstatePtr: OpaquePointer
然后可以使用,例如作为
and can then be used e.g. as
g722_coder_init(dstatePtr)
这篇关于快速访问C变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!