我一直在試圖將一個字符串發送到/從C#/從C++很長一段時間,但沒能得到它的工作尚未...如何使用DLLImport將字符串從C#傳遞到C++(以及從C++到C#)?
所以我的問題很簡單:
有誰知道一些從C#發送字符串到C++和從C++發送到C#的方式嗎?
(某些示例代碼會有幫助)
我一直在試圖將一個字符串發送到/從C#/從C++很長一段時間,但沒能得到它的工作尚未...如何使用DLLImport將字符串從C#傳遞到C++(以及從C++到C#)?
所以我的問題很簡單:
有誰知道一些從C#發送字符串到C++和從C++發送到C#的方式嗎?
(某些示例代碼會有幫助)
從C#傳遞字符串C++應該是直線前進。 PInvoke將爲您管理轉換。
從C++獲取字符串到C#可以使用StringBuilder完成。您需要獲取字符串的長度以創建正確大小的緩衝區。
這裏有一個衆所周知的Win32 API的兩個例子:
[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!");
很多在Windows API中遇到的函數都帶有字符串或字符串類型的參數。對這些參數使用字符串數據類型的問題是,.NET中的字符串數據類型在創建後是不可變的,因此StringBuilder數據類型在這裏是正確的選擇。舉一個例子檢查API函數GetTempPath()
Windows API的定義
DWORD WINAPI GetTempPath(
__in DWORD nBufferLength,
__out LPTSTR lpBuffer
);
.NET原型
[DllImport("kernel32.dll")]
public static extern uint GetTempPath
(
uint nBufferLength,
StringBuilder lpBuffer
);
用法
const int maxPathLength = 255;
StringBuilder tempPath = new StringBuilder(maxPathLength);
GetTempPath(maxPathLength, tempPath);
在C代碼:
extern "C" __declspec(dllexport)
int GetString(char* str)
{
}
extern "C" __declspec(dllexport)
int SetString(const char* str)
{
}
在.NET方面:
using System.Runtime.InteropServices;
[DllImport("YourLib.dll")]
static extern int SetString(string someStr);
[DllImport("YourLib.dll")]
static extern int GetString(StringBuilder rntStr);
用法:
SetString("hello");
StringBuilder rntStr = new StringBuilder();
GetString(rntStr);
你'const'用法是倒退。 –
@本Voigt:謝謝,修正它。 – sithereal
這些示例在VisStudio 2012中使用堆棧異常進行了分解,直到我將Cdecl添加到C#和C ...。 extern「C」__declspec(dllexport)int __cdecl SetString(...然後... [DllImport(「 YourLib.dlll「,CallingConvention = CallingConvention.Cdecl)] ... – user922020