I had problems to send a double array from one application to another (both c#).
I try format the CopyData Struct
like this:
[StructLayout(LayoutKind.Sequential)]
public struct CopyDataStruct
{
public IntPtr dwData;
public int cbData;
[MarshalAs(UnmanagedType.ByValArray, ArraySubType = UnmanagedType.R8)]
public double[] lpData;
}
In Sender Application
I fill the struct like this:
double[] a = new double[2] { 1.0, 2.0 };
int size = Marshal.SizeOf(typeof(double)) * a.Count();
CopyDataStruct copyDataStruct;
copyDataStruct.dwData = IntPtr.Zero;
copyDataStruct.lpData = a;
copyDataStruct.cbData = size;
int result = SendMessage(hWnd, WM_COPYDATA, 0, ref copyDataStruct);
In Receiver Application
, I try this:
private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
{
switch (msg)
{
case (int)WINMESSAGES.WM_COPYDATA:
CopyDataStruct cp = (CopyDataStruct)Marshal.PtrToStructure(lParam, typeof(CopyDataStruct));
break;
}
return IntPtr.Zero;
}
but in cp.lpDat
a value comes null
. I don't know if I sent wrong or if I received wrong. Please help, thanks.
You need to use native memory. Passing C#
double[]
like that wont work. It will be garbage collected(heck, it's not even allocated in C# - it's just in stack). You can either pin the object with unsafe/fixed keywords or useAllocHGlobal
.This is some code I ripped from Internets. Demonstrates sending part:
Taken: http://code.msdn.microsoft.com/windowsdesktop/CSReceiveWMCOPYDATA-dbbc7ed7