2011-06-26 40 views
1

**這仍然沒有解決**麻煩與字節數組中ObjC/C++編組到C#在IOS

我試圖調用從C#的ObjC/C++函數的代碼。我做我最好按照不同的示例代碼,最近一次是大多來自:

http://msdn.microsoft.com/en-us/library/ms146631(v=VS.80).aspx

這是爲iPhone/MonoTouch的環境,所以我不知道我所做的一切,我應該。的字節則出現是確定在ObjC/C++函數,但字節數組我回來到C#結束含有0 0 0 0 0 0等

** **更新

更正for循環初始化,現在它在* returnbytes [i] = bytes [i]上給出一個EXC_BAD_ACCESS信號;線。

C#代碼:

[DllImport ("__Internal")] 
private static extern int _getjpeg(string url,ref IntPtr thebytes); 

void somefunction(string image_id) { 
    int maxsize = 50000; 

    byte[] thebytes = new byte[maxsize]; 
    IntPtr byteptr = Marshal.AllocHGlobal(maxsize); 

    int imagesize = _getjpeg(image_id,ref byteptr); 

    Debug.Log("Getting _picturesize()... "+ image_id); 
    int picsize = _picturesize(); 

    Marshal.Copy(byteptr,thebytes,0,picsize); 

    var texture = new Texture2D(1,1); 

    string bytedebug = ""; 
    for (int i=5000 ; i < 5020 ; i++) 
     bytedebug+=thebytes[i] + " "; 

    Debug.Log("Bytes length is "+imagesize); 
    Debug.Log("Bytes content is "+bytedebug); 
} 

C++/ObjC代碼:

int _getjpeg(const char* url,unsigned char** returnbytes) { 

    ALAsset* asset = [_pictures objectForKey:[NSString stringWithUTF8String:url]]; 

    if(asset != NULL) 
     NSLog(@"_getjpeg() found URL: %@",[NSString stringWithUTF8String: url]); 
    else { 
     NSLog(@"_getjpeg() could not find URL: %@",[NSString stringWithUTF8String: url]); 
     return NULL; 
    } 

    UIImage *image = [UIImage imageWithCGImage: [asset thumbnail]]; 
    NSData* pictureData = UIImageJPEGRepresentation (image, 1.0); 

    picturesize = (int)[pictureData length]; 

    unsigned char* bytes = (unsigned char*)[pictureData bytes]; 

    // This test does not give EXC_BAD_ACCESS 
    *returnbytes[5] = (unsigned int)3; 

    // updated below initializer in below for loop according to Eikos suggestion 
    for(int i=0 ; i < picturesize ; i++) { 
     // below lines gives EXC_BAD_ACCESS 
     *returnbytes[i] = bytes[i];    
    } 

    NSString* debugstr = [NSString string]; 

    for(int i=5000; i < 5020 ; i++) { 
     unsigned char byteint = bytes[i]; 
     debugstr = [debugstr stringByAppendingString:[NSString stringWithFormat:@"%i ",byteint]]; 

    } 


    NSLog(@"bytes %s",[debugstr UTF8String]); 
    return picturesize; 
} 

感謝

回答

1

記住的是,JPGRepresentation可能是不完全一樣的,你投入了,所以長度可能不同。

for(int i;i < picturesize;i++) { 
    // *** Not sure I'm doing this correctly *** 
    *returnbytes[i] = bytes[i];    
} 

你忘了初始化i,所以它可能會比picturesize更大的隨機值開始,因此該循環將無法運行。

+0

謝謝,這真是愚蠢的我。更正它,現在它給* returnbytes [i] = bytes [i]上的EXC_BAD_ACCESS信號;線。 – Aicos

+0

returnbytes足夠大嗎? – Eiko

+0

我應該這樣想。我用C#初始化它。在C#中嘗試了幾個大小。最後一個是:\t \t IntPtr byteptr = Marshal.AllocHGlobal(500000 * Marshal.SizeOf(samplearray [0])); \t \t \t \t int imagesize = _getjpeg(image_id,ref byteptr); – Aicos

0

你想要unsigned char*而不是**。您正在傳遞已分配的指針。 A **適用於傳遞指向變量的指針,變量本身是指向數據的指針:即,當被調用者將分配內存並且調用者想知道它時。

只是通過在無符號字符*,然後使用

returnbytes[i] = bytes[i]; 

或者,在飛翔距離分配並使用出來,而不是一個REF。