Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
433 views
in Technique[技术] by (71.8m points)

swift3 - Access C variable in swift

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).

Compiler error

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"
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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;

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...