2012-12-21 85 views
3

可能重複:
Passing char pointer from C# to c++ function傳遞字符指針從C#到C++

我有這種類型的問題:

我有與此簽名C++函數:

int myfunction (char* Buffer, int * rotation) 

該bu FFER參數必須充滿空間字符(0x20的十六進制)

在C++中,我可以簡單地解決這樣的問題:

char* buffer = (char *)malloc(256); 
memset(buffer,0x20,256); 
res = myfunction (buffer, rotation); 

我試圖調用從C#此功能。

這是我的P/Invoke聲明:

[DllImport("mydll.dll", CharSet = CharSet.Ansi, SetLastError = true)] 
private static extern unsafe int myfunction (StringBuilder Buffer, int* RotDegree); 

在我的C#類我試着這樣做:

StringBuilder buffer = new StringBuilder(256); 
buffer.Append(' ', 256); 
... 
myfunction(buffer, rotation); 

,但它不工作....

任何人都可以幫助我?

謝謝。

+2

「但它不起作用」沒有幫助。 – PhoenixReborn

+3

你甚至沒有顯示p/invoke聲明!沒有這樣的基本信息,我們無法幫助您。 –

+0

@FrancisP這個問題不是那個問題的重複! –

回答

5

你的p/invoke看起來不太正確。它應該(推測)使用Cdecl調用約定。你不應該使用SetLastError。並且不需要不安全的代碼。

我會寫這樣的:

[DllImport("mydll.dll", CallingConvention=CallingConvention.Cdecl)] 
private static extern int myfunction(StringBuilder Buffer, ref int RotDegree); 

然後調用它像這樣:

StringBuilder buffer = new StringBuilder(new String(' ', 256)); 
int rotation = ...; 
int retVal = myfunction(buffer, ref rotation); 

我沒有指定CharSet因爲Ansi是默認的。

+0

**謝謝David!** – betelgeuse

0

嘗試通過rotation作爲參考。您可能還需要編輯myfunction的簽名。請讓我知道該方法是否有效。

myfunction (buffer.ToString(), ref rotation);