关于c++向c#传送字符串的问题
关于c++向c#传送字符串的问题我在C程序里代码如下
HWND hWnd = FindWindow(NULL,_T("WawaApp"));
char *str = new char[3];
str = "123";
SendMessage(hWnd,WM_WAWADEFMSG,(WPARAM)str,strlen(str));
c#代码如下
[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
static extern int RegisterWindowMessage(string lpString);
private readonly int WM_WAWADEFMSG = RegisterWindowMessage("WawaDefMsg");
public Form1()
{
InitializeComponent();
}
protected override void WndProc(ref Message m)
{
if(m.Msg == WM_WAWADEFMSG)
{
int len = m.LParam.ToInt32();
string str = Marshal.PtrToStringUni(m.WParam, len );
MessageBox.Show(str);
return;
}
base.WndProc(ref m);
}
可怎么也得不到c里面传过来的值,C里面我用PostMessage和SendMessage都试过了,c#里用 Marshal.PtrToStringUni,Marshal.PtrToStringAnsi,Marshal.PtrToStringAuto等也都试过了,都不行。 --------------------编程问答-------------------- 我改成下面这样也不行,是不是进程间的指针不一样呀。
char *str = new char[3];
strcpy(str,"123"); --------------------编程问答-------------------- 用SendMessage不能传指针,因为指针是指向本身进程的某个地址,跨进程传递的时候,传过去的是本进程的某个地址,而目标进程是不能访问本进程地址空间的,会出错。 --------------------编程问答-------------------- c代码如下
const UINT WM_WAWADEFMSG = ::RegisterWindowMessage(_T("WawaDefMsg"));
int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
{
int nRetCode = 0;
// 初始化 MFC 并在失败时显示错误
if (!AfxWinInit(::GetModuleHandle(NULL), NULL, ::GetCommandLine(), 0))
{
// TODO: 更改错误代码以符合您的需要
_tprintf(_T("错误: MFC 初始化失败\n"));
nRetCode = 1;
}
else
{
LPCWSTR str = _T("hello中国!");
int id = GlobalFindAtom(str);
HWND hWnd = FindWindow(NULL,_T("WawaApp"));
if(id == 0)
{
id = GlobalAddAtom(str);
}
SendMessage(hWnd,WM_WAWADEFMSG,id,lstrlen(str));
}
return nRetCode;
}
c#代码如下
public partial class Form1 : Form
{
[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
static extern int RegisterWindowMessage(string lpString);
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
public static extern long GlobalGetAtomName(Int32 atom, StringBuilder lpBuffer, int size);
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
public static extern Int32 GlobalDeleteAtom(Int32 atom);
private readonly int WM_WAWADEFMSG = RegisterWindowMessage("WawaDefMsg");
public Form1()
{
InitializeComponent();
}
protected override void WndProc(ref Message m)
{
if(m.Msg == WM_WAWADEFMSG)
{
int atom = m.WParam.ToInt32();
int len = m.LParam.ToInt32();
StringBuilder buffer = new StringBuilder(len);
GlobalGetAtomName(atom, buffer, len);
MessageBox.Show(buffer.ToString());
GlobalDeleteAtom(atom);
return;
}
base.WndProc(ref m);
}
}
补充:.NET技术 , C#