Home > Software design >  Obj-c( ) calling api with reference to a pointer
Obj-c( ) calling api with reference to a pointer

Time:09-16

Quite new to Objective-C/Objective-C , I am writing a wrapper around a C library.

One of the functions takes a reference to a pointer and a reference to an int to create a buffer and return its size, in this manner :

int GetData(char*& pcBuffer, int& iBufferSize);

It is really not clear to me as to how to interface with this via Objective-C/C

Upto now, I have been writing calls like this

-(int) GetData: (NSString*) pcData
              : (int) iBufferSize;

However, as the pointer referenced by pcBuffer will be created and filled in by the library code, what should I be using as a data type ?

In addition, as the int is passed as a reference and not as a pointer, how do I declare that correctly ?

Any help possible for this ?

CodePudding user response:

The C function likely allocates the string buffer and returns it in the first argument, while returning the size of the allocated buffer in the second argument.

You don't need to mimic the same interface on the Objective-C side, as you can use the returned buffer to instantiate a NSString. What's left is to cope with the return value of the function, which I assume it's an error code in case something goes wrong:

- (nullable NSString *)getDataWithError:(NSError **)error {
    char *buffer;
    int size;
    int errCode = GetData(buffer, size);
    if (errCode == 0) {
        return [NSString stringWithCString:buffer encoding:NSUTF8StringEncoding];
    } else {
        if (error) {
            *error = [NSError errorWithDomain:MyErrorDomain code: errCode userInfo:nil];
        }
        return nil;
    }
}

As a bonus, thanks to the error reporting mechanism in place, the above function can be nicely called from swift:

let value = try MyObject().getData()
  • Related