2015-06-24 19 views
0

我試圖做一個函數P在Ubuntu 14.04 /調用使用單聲道:的IntPtr沒有正確單封

[DllImport(@"libRT", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)] 
    private static extern uint DoChallenge(
     IntPtr pEncryptedBlob, 
     uint dwEncryptedBlobLen, 
     IntPtr pDecryptedBlob, 
     uint dwMaxLen, 
     ref uint dwDecryptedBlobLen); 

之前我調用在C#中的功能,我打印的加密和解密值:

Console.WriteLine(pEncryptedBlob.ToString()); // value is 140640247632608 
Console.WriteLine(pDecryptedBlob.ToString()); // values is 140640247634240 

// Do the challenge 
this.errorCode = DoRtasChallenge(pEncryptedBlob, pDecryptedBlob, 
        (uint)this.decryptedBlobBuffer.Length, 
        ref this.decryptedBlobReturnLength); 

現在,在C++代碼我打印,我收到值:

APIFUNC uint32_t DoChallenge(unsigned char * pEncryptedBlob,long dwEncryptedBlobLen,unsigned char * pDecryptedBlob,long dwMaxLen,long * dwDecryptedBlobLen) 
{ 
    fprintf(stderr, "pEncryptedBlob: %ld \n",pEncryptedBlob); 
    fprintf(stderr, "pDecryptedBlob: %ld \n",pDecryptedBlob); 

    // the output: 
    // pEncryptedBlob: 1 
    // pDecryptedBlob: 140640603072256 
} 

因此,它看起來既像IntPtrs都是getti在編組期間修改。

我認爲這是因爲Mono/Ubuntu 14.04 64位環境而發生的,因爲它適用於Windows和Ubuntu 14.04 32位。

解決方法的任何想法?非常感謝

+0

什麼是' APIFUNC'? –

+0

#define APIFUNC extern「C」__declspec(dllexport) – inside

+2

我對編組知之甚少,但我敢肯定,'sizeof(long)'是8.它位於我的64位Ubuntu系統下的gcc下。使用'int'或者''中的一個大小類型。或者在C#中創建兩個版本的函數並調用正確的函數。 –

回答

1

要刪除特定於平臺的實現,以便您的C#& c/cpp代碼將運行xplat,您應該將C#「System.String」傳遞給「const char * src」。 Interop編組將處理其餘的問題。

Ç簽名:

private static extern void myCfunc (string src, uint n); 

用法:

void myfunc (const char *src, size_t n); 

C#中的DllImport

var myString = "Test"; 
myCfunc(myString, myString.Length); 

互操作與本機庫: http://www.mono-project.com/docs/advanced/pinvoke/

+0

謝謝,這很有用 – inside

+0

很高興你能工作 – SushiHangover

-1

我只是找到了一個解決辦法,我強迫我IntPtrs被編組爲4個字節:

[DllImport(@"libRT", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)] 
private static extern uint DoChallenge(
    [MarshalAs(UnmanagedType.U4)] // this is a fix 
    IntPtr pEncryptedBlob, 
    uint dwEncryptedBlobLen, 
    [MarshalAs(UnmanagedType.U4)] 
    IntPtr pDecryptedBlob, 
    uint dwMaxLen, 
    ref uint dwDecryptedBlobLen); 

結果:

C#結果:

139700723537696 
139700723538064 

C++結果:

pEncryptedBlob: 139700723537696 
pDecryptedBlob: 139700723538064