2012-11-06 50 views
3

需要在c函數中生成一些隨機的10字節長度的字符串並從objective-c調用該函數。所以,我創建了一個指向uint8_t的指針並將它傳遞給C函數。該函數生成隨機字節並將它們分配給* randomString。但是,從函數返回到objective-c後,randomValue指針指向NULL。如何將生成的數組從c函數返回到objective-c

這裏是我的隨機函數在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++; 
    } 
} 

下面是Objective-C的部分:

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

NSString *randomString = [[NSString alloc] initWithBytes:randomValue length:10 encoding:NSASCIIStringEncoding]; 
NSLog(@"Random string: %@", randomString); 

回答

2

指針是按值傳遞的,所以randomValue會的randomString通話後仍然NULL。您需要將指針傳遞給一個指針,以使其工作:

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); 
+0

究竟是我在想什麼! :) – haroldcampbell

3

一個更自然的語義,像malloc()本身是:

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; 
} 
+0

這也工作,並讀取更好'uint8_t * randomValue = randomString();' – haroldcampbell

1

你也許應該使用uint8_t **randomeValue代替uint8_t *