2014-09-16 1 views
0

C 배열에서 액세스해야하는 자체 객체가 포함 된 NSArray *가 있습니다. C 함수에서 내 객체를 치면 잘 작동하지만 C 배열에 복사하려고하면 잠시 후 포인터가 지워진다는 것을 알 수 있습니다!ARC를 사용하여 NSArray를 C 배열로 바꿈

@interface MNCircularBufferPlayer;// just assume this exists 

void schedule(MNPlayList* playlist){ /* some C code */} 

typedef struct MNPlayList { 
    __unsafe_unretained MNCircularBufferPlayer **players; 
    int playersCount; 
} MNPlayList; 

-(void)sendToCApi(){ 
//...  
    NSArray* toCopy = self.players; // array of MNCircularBufferPlayer instances 
    MNPlayList* playlist=malloc(sizeof(MNPlaylist)); 
    playlist->playersCount=toCopy.count; 
    playlist->players=(__unsafe_unretainedNCircularBufferPlayer**)calloc(toCopy.count+1,sizeof(MNCircularBufferPlayer*)); 
    for(MNCircularBufferPlayer* player in toCopy){ 
     playlist->players[i]=player; 
    } 
    //.. send to C api 
} 

이 시점 이후에 메모리를 검사하면 내 구조체에 포함 된 버퍼가 정상적으로 보입니다. 그러나 C 함수가 동일한 구조체를 가져올 때 구조체의 크기는 같지만 버퍼의 내용은 모두 0x30000000입니다! 나는 MNCircularBufferPlayer 인스턴스가 여전히 유지된다는 것을 전적으로 긍정적입니다! 이 할당 해제의 경우에도 중단 점은 내가-준 최대 대신에 연결된 목록을 사용하여 종료

... 단지 100 % 확실하게, 그리고 그것을 작동 :

typedef struct MNPlayList { 
    __unsafe_unretained MNCircularBufferPlayer *player; 
    struct MNPlayList *next; 
} MNPlayList; 

하지만이 잠을 잃고 있어요 하나. NSArray의 개체로

답변

1

이것은 nil 등으로 MNCircularBufferPlayer * 객체의 배열을 생성합니다 ... 당신이 실제로 C에서 이러한 개체를 어떻게 사용할지 분명하지 않다, 그러나 어쨌든, 오브젝티브 C 오브젝트해야합니다 마지막 요소는 파생물 :

-(void)sendToCApi(){ 
    MNCircularBufferPlayer *carray = malloc(sizeof(MNCircularBufferPlayer *) * ([self.players count] + 1])); 
    for (NSUInteger i = 0; i < [self.players count]; i++) 
     carray[i] = self.players[i]; 
    carray[[self.players count]] = nil; 

    //.. send to C api 

    free(carray); 
}