且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用DLLImport从C#传递字符串到C ++(和从C ++到C#)?

更新时间:2023-02-12 15:45:05

将字符串从C#传递到C ++应该是简单的。 PInvoke将为您管理转换。

Passing string from C# to C++ should be straight forward. PInvoke will manage the conversion for you.

从C ++到C#的获取字符串可以使用StringBuilder完成。

Geting string from C++ to C# can be done using a StringBuilder. You need to get the length of the string in order to create a buffer of the correct size.

下面是一个众所周知的Win32 API的两个例子:

Here are two examples of a well known 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!");