我一直在试图将一个字符串发送到/从C#/从C ++很长一段时间,但没能得到它的工作尚未...
所以我的问题很简单:
有谁知道某种方式将一个字符串发送从C#和C ++和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!");
在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);
很多那些在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);