C # SendMessage for C ++ WinProc

I need to send a string from C # to C ++ WindowProc. There are a number of related SO questions related to this, but none of the answers 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 tried several different things: Marshalling string like LPStr, LPWStr, also tried to create IntPtr from unmanaged memory and write it with Marshal.WriteByte.

A pointer is a valid memory cell on the C ++ side, but there is no data there. What am I missing?

+4
source share
2 answers

For C ++ LPWSTR or LPSTR you need to use C # StringBuilder in your DllImport.

For C ++ LPCWSTR or LPCSTR you need to use C # string in your DllImport.

+2
source

Make sure your SendMessage call comes in the expected synchronous mode and that your NativeMethods class displays the correct Win32 call (Send or PostMessage.) If this is not true, it is possible that by the time you process your message at the end of C ++, you have left the scope of your C # method and all local variables created on the stack disappeared, resulting in your bad pointer appearing.

Stack and heap combinations for cross-thread calls: Threads have their own stacks but share a heap. The variables listed on the stack in one thread will not be visible in another. String type is an odd duck in .NET. This is a reference type based on Object, but created to look and feel like a value type in code. Thus, perhaps passing a pointer to the data associated with the heap should work. That StringBuilder, as the reference type assigned by the heap, is included.

+1
source

Source: https://habr.com/ru/post/1307153/


All Articles