I need to send a string from C# to a C++ WindowProc. There are a number of related questions on SO related to this, but none of the answers have worked for me. Here's the situation:
PInvoke:
[DllImport("user32", CharSet = CharSet.Auto)]
public extern static int SendMessage(IntPtr hWnd, uint wMsg, IntPtr wParam, string lParam);
C#:
string lparam = "abc";
NativeMethods.User32.SendMessage(handle, ConnectMsg, IntPtr.Zero, lparam);
C++:
API LRESULT CALLBACK HookProc (int code, WPARAM wParam, LPARAM lParam)
{
if (code >= 0)
{
CWPSTRUCT* cwp = (CWPSTRUCT*)lParam;
...
(LPWSTR)cwp->lParam <-- BadPtr
...
}
return ::CallNextHookEx(0, code, wParam, lParam);
}
I've tried a number of different things, Marshalling the string as LPStr, LPWStr, also tried creating an IntPtr from unmanaged memory, and writing to it with Marshal.WriteByte.
The pointer is the correct memory location on the C++ side, but the data isn't there. What am I missing?