Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return generated array from c function to objective-c

Tags:

c

objective-c

Need to generated some random 10 byte length string in c function and call the function from objective-c. So, I'm creating a pointer to uint8_t and passing it to C function. The function generates random bytes and assigns them to *randomString. However, after returning from function to objective-c randomValue pointer points to NULL.

Here's my random function in C:

void randomString(uint8_t *randomString)
{
  randomString = malloc(10);

  char randomByte;
  char i;
  for (i = 0; i < 10; i++) {

    srand((unsigned)time(NULL));
    randomByte = (rand() % 255 ) + 1;
    *randomString = randomByte;
    randomString++; 
  }
} 

Here's objective-c part:

uint8_t *randomValue = NULL;
randomString(randomValue); //randomValue points to 0x000000

NSString *randomString = [[NSString alloc] initWithBytes:randomValue length:10 encoding:NSASCIIStringEncoding];
NSLog(@"Random string: %@", randomString);
like image 462
Centurion Avatar asked Jan 19 '26 02:01

Centurion


2 Answers

A more natural semantic, like malloc() itself would be:

uint8_t * randomString()
{
    uint8_t *randomString = malloc(10);
    srand((unsigned)time(NULL));
    for (unsigned i = 0; i < 10; i++)
        randomString[i] = (rand() % 254) + 1;
    return randomString;
}
like image 102
trojanfoe Avatar answered Jan 21 '26 19:01

trojanfoe


Pointers are passed by value, so randomValue will remain NULL after the call of randomString. You need to pass a pointer to a pointer in order to make it work:

void randomString(uint8_t **randomString) {
    *randomString = malloc(10);
    // ... the rest of your code goes here, with an extra level of indirection
}

uint8_t *randomValue = NULL;
randomString(&randomValue);
like image 26
Sergey Kalinichenko Avatar answered Jan 21 '26 19:01

Sergey Kalinichenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!