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

问题描述:

我一直试图发送字符串/从C#到/从C ++很长一段时间,但没有设法让它工作...

I've been trying to send a string to/from C# to/from C++ for a long time but didn't manage to get it working yet ...

所以我的问题很简单:

有人知道从C#到C ++和从C ++到C#的一个字符串吗?

(一些示例代码会很有帮助) / p>

So my question is simple :
Does anyone know some way to send a string from C# to C++ and from C++ to C# ?
(Some sample code would be helpful)

将字符串从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!");