背景
- 我的服务端是一个C#进程;
- 我的客户端是一个C++进程;
- 我需要C#进程给C++发送结构体。
代码
C#代码
namespace Server
{
public partial class MainWindow : Window
{
[DllImport("user32.dll")]
private static extern int SendMessage(IntPtr hwnd, uint wMsg, int wParam, ref COPYDATASTRUCT lParam);
[StructLayout(LayoutKind.Sequential)]
public struct PWGREENLINESTRUCT
{
public double x;
public double y;
}
private byte[] StructToBytes(object anyStruct)
{
int size = Marshal.SizeOf(anyStruct);
IntPtr bytesPtr = Marshal.AllocHGlobal(size);
Marshal.StructureToPtr(anyStruct, bytesPtr, false);
byte[] bytes = new byte[size];
Marshal.Copy(bytesPtr, bytes, 0, size);
Marshal.FreeHGlobal(bytesPtr);
return bytes;
}
public void SendMessage()
{
PWGREENLINESTRUCT _struct = new PWGREENLINESTRUCT();
_struct.x = 10.0f;
_struct.y = 20.0f;
var structBytes = StructToBytes(_struct);
COPYDATASTRUCT pw_struct;
pw_struct.dwData = (IntPtr)0;
pw_struct.cbData = structBytes.Length;
pw_struct.lpData = Marshal.AllocHGlobal(pw_struct.cbData);
Marshal.Copy(structBytes, 0, pw_struct.lpData, structBytes.Length);
SendMessage(proxyHandle, WM_COPYDATA, 0, ref pw_struct);
Marshal.FreeHGlobal(pw_struct.lpData);
}
}
}
C++代码
BEGIN_MESSAGE_MAP(CDlgPalmProbe, CDialogEx)
ON_WM_COPYDATA()
END_MESSAGE_MAP()
struct PWGREENLINESTRUCT
{
double _x = 0;
double _y = 0;
}
BOOL CDlgPalmProbe::OnCopyData(CWnd* pWnd, COPYDATASTRUCT* pCopyDataStruct)
{
if (pCopyDataStruct)
{
if (pCopyDataStruct->dwData == 0)
{
unsigned char* pSource = (unsigned char*)(pCopyDataStruct->lpData);
PWGREENLINESTRUCT _struct;
memcpy(&_struct, (PWGREENLINESTRUCT*)pSource, sizeof(PWGREENLINESTRUCT));
printf("x = %f, y = %f\n", _struct._x, _struct._y);
}
}
}
注意
- 传输图像或者其它数据也是一样的,想办法将数据转换成byte[],然后按照上述方法传输即可。