在Swift中访问C变量 [英] Access C variable in swift
问题描述
我试图访问一个状态变量在.h文件中声明,但编译器说这个变量不存在。我是否需要在桥接头文件中添加任何内容?
在我的swift文件中,我无法访问 dstate 或 cstate
编译器在 g722_coder_init(& dstate)$>行上使用未解析的标识符dstate' c $ c>。
头文件
#ifdef __cplusplus
externC{
#endif
extern struct g722_dstate dstate;
extern结构体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
桥接标题
#importg722_codec.h
是
$ c $问题是struct g722_dstate 一个不完整的类型
和Swift不能导入一个不完整类型的变量,只有变量
是指针到一个不完整类型(以及那些导入
为OpaquePointer
)。
将完整的结构定义添加到导入的头文件中
是最简单的解决方案。
如果这是不可能的,那么一种解决方法是添加
#importg722_codec.h
static struct g722_dstate * __nonnull dstatePtr =& dstate;
添加到桥接头文件中,该文件定义了一个变量,其中包含不透明
dstate
变量。这被导入到Swift中作为var dstatePtr:OpaquePointer
,然后可以使用例如作为
g722_coder_init(dstatePtr)
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 ?
In my swift file I can't access dstate or cstate
The compiler says "Use of unresolved identifier 'dstate'" on the line
g722_coder_init(&dstate)
.Header file
#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
Bridging Header
#import "g722_codec.h"
解决方案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 asOpaquePointer
).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;
to the bridging header file, which defines a variable containing the address of the "opaque"
dstate
variable. This is imported to Swift asvar dstatePtr: OpaquePointer
and can then be used e.g. as
g722_coder_init(dstatePtr)
这篇关于在Swift中访问C变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!