Access C Variable in Swift

Access C variable in swift

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)

How to read C global variables from swift?

You may try to declare variable extern in MySwift2-Bridging-Header.h, but I don't think it will work:

#define size 5
extern int buf[size];
void add();

One clean way to read or write a global variable in C is to make functions to do it:

/* Csource.c: */

int get_buf(int i)
{
if (i >= 0 && i < 5)
return buf[i];
else
return 0;
}

void set_buf(int i, int value)
{
if (i >= 0 && i < 5)
buf[i] = value
}

How to access a private objective C variable in Swift View Controller?

Moving the property to the .h. exposes it publicly and also makes it available to the .m because the .m file by default imports the .h.
Example:

// CameraViewController.h
@interface CameraViewController : UIViewController
@property (nonatomic, strong) AVCaptureSession *session;
@end

// CameraViewController.m
#import "CameraViewController.h" // <- notice the import, `session` is accessible internally.

As for the session property being nil it may be because you have not initialized it with a value yet. In your init you may want to initialize session with [[AVCaptureSession alloc] init]

Note: to avoid potential problems with unintended mutability I recommend asking your self if you can make publicly exposed properties read only i.e.

@property (nonatomic, strong, readonly) AVCaptureSession *session;

Cannot access Swift var from Objective-C View controller - iOS

You will have to declare the variable as public.

By default, the variables have internal access, that means they can be accessed only from inside their module. Obj-C code is not in their module.



Related Topics



Leave a reply



Submit