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

24

我一直试图将字符串从C#发送到C++,并从C++发送到C#,但长时间以来都无法使其正常工作...

因此,我的问题很简单:
有人知道如何从C#发送字符串到C++,并从C++发送字符串到C#吗?
(提供一些示例代码会很有帮助)

3个回答

21

在你的 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);

1
你的 const 使用方式是反过来的。 - Ben Voigt
这些例子在VisStudio 2012中出现了堆栈异常,直到我在C#和C++中都添加了cdecl。... extern "C" __declspec(dllexport) int __cdecl SetString(...然后...[DllImport("YourLib.dlll", CallingConvention = CallingConvention.Cdecl)]... - user922020

12

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

从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!");

1
许多在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);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接