2010-12-08 116 views
2

我被困在c#實現端,因爲我對它很新穎。問題是,我想從c#代碼傳遞一個'指針'(有內存),這樣My C++應用程序就可以將pchListSoftwares緩衝區複製到pchInstalledSoftwares。我無法弄清楚如何從C#端傳遞指針。將C#中的字符指針傳遞給C++函數

本地C++代碼(MyNativeC++ DLL.dll)

void GetInstalledSoftwares(char* pchInstalledSoftwares){ 
    char* pchListSoftwares = NULL; 
    ..... 
    ..... 
    pchListSoftwares = (char*) malloc(255); 

    /* code to fill pchListSoftwares buffer*/ 

    memcpy(pchInstalledSoftwares, pchListSoftwares, 255); 

    free(pchListSoftwares); 

} 

傳遞簡單的 '串' 是不工作...

C#實現

[DllImport("MyNativeC++DLL.dll")] 
private static extern int GetInstalledSoftwares(string pchInstalledSoftwares); 


static void Main(string[] args) 
{ 
......... 
......... 
     string b = ""; 
     GetInstalledSoftwares(0, b); 
     MessageBox.Show(b.ToString()); 
} 

任何形式的幫助非常感謝...

回答

2

嘗試使用一個StringBuilder

[DllImport("MyNativeC++DLL.dll")] 
private static extern int GetInstalledSoftwares(StringBuilder pchInstalledSoftwares); 


static void Main(string[] args) 
{ 
......... 
......... 
     StringBuilder b = new StringBuilder(255); 
     GetInstalledSoftwares(0, b); 
     MessageBox.Show(b.ToString()); 
} 
1

我的錯誤...刪除0致電GetInstalledSoftwares(0, b);

+0

幹得好(計算出來) – 2010-12-08 16:28:29

0

嘗試改變原型行:

private static extern int GetInstalledSoftwares(ref string pchInstalledSoftwares); 

(通過引用發送字符串)。