Passando stringa da C# per C++ dovrebbe essere semplice. PInvoke gestirà la conversione per te.
L'acquisizione di una stringa da C++ a C# può essere eseguita utilizzando StringBuilder. È necessario ottenere la lunghezza della stringa per creare un buffer della dimensione corretta.
Ecco due esempi di un noto API Win32:
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount);
public static string GetText(IntPtr hWnd)
{
// Allocate correct string length first
int length = GetWindowTextLength(hWnd);
StringBuilder sb = new StringBuilder(length + 1);
GetWindowText(hWnd, sb, sb.Capacity);
return sb.ToString();
}
[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
public static extern bool SetWindowText(IntPtr hwnd, String lpString);
SetWindowText(Process.GetCurrentProcess().MainWindowHandle, "Amazing!");
fonte
2012-05-29 13:06:42
vostro 'utilizzo const' è indietro. –
@Ben Voigt: grazie, risolto. – sithereal
Questi esempi sono esplosi con le eccezioni di stack in VisStudio 2012 fino a quando ho aggiunto cdecl sia al C# che al C .... extern "C" __declspec (dllexport) int __cdecl SetString (... e poi ... [DllImport (" YourLib.dlll ", CallingConvention = CallingConvention.Cdecl)] ... – user922020