Need help turning a C function into an Objective C

2019-09-19 14:39发布

I have a function written in C that is rather large and currently is only running in the main() function of a C file while I have been using to test it out. Here is it's declaration

void getData(const char* encodedBuffer, int user);

If you would like to see the contents of getData Here is the pastebin for it.

As of now I'm just passing in encodedBuffer which I will have a global variable that is getting updated by the getData function.

I would like to know what the proper way is to turn a C based function like this into a Objective-C protocol method. Right now I'm setting it up like this

iDriver.h (my interface/protocol)

#import <Foundation/Foundation.h>

@protocol iDriver <NSObject>
-(void)getData;
-(void)cancel;

@end

DriverOne.h (Class that actually implements the protocol method)

#import <Foundation/Foundation.h>
#import "iDriver.h"

@interface DriverOne : NSObject <iDriver>

@end

DriverOne.m

#import "DriverOne.h"

@implementation DriverOne

enum Status getData(char* encodedBuffer, int user)
{
    // Copy C code which I showed in the link earlier
    // to above into this method. I will want it to return a status
    // and populate a global variable with the data.
}

My thought is that I shouldn't really run into any issues doing this since Objective-C is a superset of C but just copying the C code into a method like that be problematic?

1条回答
Lonely孤独者°
2楼-- · 2019-09-19 15:27

When porting a C function to an ObjC method, it's just a tweak to the signature. In your case, you'll change:

enum Status getData(char* encodedBuffer, int user)

to something like:

- (enum Status) getData: (char*) encodedBuffer user: (int) user

Objective C methods are always denoted with a - at the beginning (class methods start with a +). If you want to specify the type, you put in parens (otherwise it's assumed to be type id which is generic for "object"). And you have to keywordize your function name. One keyword for each argument.

Then just like C, you can just copy paste that line into your header file:

@protocol iDriver <NSObject>
- (enum Status) getData: (char*) encodedBuffer user: (int) user;
@end

After that just copy the guts inside the method.

It's not clear how familiar you are with the ideas behind OO and instances, but using it might look something like:

DriverOne *driverOneObject = [[DriverOne alloc] init];
char *buffer = malloc(YOUR_BUFFER_SIZE);
enumStatus status = [driverObject getData: buffer user: SomeUserThing];

Coming full circle, is there a reason you want this to be reified (turned into objects)? I'm all for lots of objects myself, but one of the features of ObjectiveC, is that it IS a superset of C. You can just use your function as is from your C prototype. You don't have to wrap it up in an ObjectiveC object, unless you see an advantage to doing so.

查看更多
登录 后发表回答