快速访问 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)
行上显示使用未解析的标识符 '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屋!