2015-09-27 32 views
0

我在寫一個使用C++類庫的c#控制檯應用程序。在C++語言類庫我有一個方法:在c中使用C++方法#

public:bool GetMDC(char fileName[], char mdcStrOut[]){ 
    // My Code goes Here 
} 

此方法在fileName參數文件路徑和mdcStrOut把一個值。

我將這個類庫添加爲我的C#控制檯應用程序的引用。當我想調用GetMDC方法時,該方法需要兩個參數sbyte。所以它在c#中的簽名是GetMDC(sbyte* fileName, sbyte* mdcStrOut)

我的代碼如下所示:

unsafe{ 
    byte[] bytes = Encoding.ASCII.GetBytes(fileName); 
    var _mdc = new TelsaMDC.TelsaMDCDetection(); 
    var outPut = new sbyte(); 
    fixed (byte* p = bytes) 
    { 
     var sp = (sbyte*)p; 
     //SP is now what you want 
     _mdc.GetMDC(sp, &outPut); 
    } 
} 

它的工作原理沒有錯誤。但問題是,outPut變量只包含mdcStrOut的第一個字符。我不熟悉C++。我知道我將內存地址output傳遞給GetMDC。那麼如何在我的控制檯應用程序中獲得它的價值呢?

編輯當我宣佈output變量這樣var outPut = new sbyte[MaxLength]我得到_mdc.GetMDC(sp, &outPut);行上&標誌錯誤

。它說:Cannot take the address of, get the size of, or declare a pointer to a managed type ('sbyte[]')

回答

1

變量outPut是一個單字節。 您需要創建一個接收緩衝區,例如,var outPut = new sbyte[MaxLength]

unsafe{ 
    byte[] bytes = Encoding.ASCII.GetBytes(fileName); 
    var _mdc = new TelsaMDC.TelsaMDCDetection(); 
    var outPut = new sbyte[256]; // Bad practice. Avoid using this! 
    fixed (byte* p = bytes, p2 = outPut) 
    { 
     var sp = (sbyte*)p; 
     var sp2 = (sbyte*)p2; 
     //SP is now what you want 
     _mdc.GetMDC(sp, sp2); 
    } 
} 

另外,我建議重寫代碼,以避免可能出現的緩衝區溢出,因爲函數GetMDC不知道緩衝區的大小。

+0

它不起作用。請參閱編輯。 – Beginner

+0

就像第一個參數'bytes'一樣 –