0

Using SendMessageW function I am passing c# string as a parameter to c++ function. I am typecasting to CString in c++ but it's value is empty. Please check below code and provide solution

-----------------------c# code ------------------

public unsafe IntPtr Testing()
{

  string string_aux = "Stringtochange";
  void* pt = Marshal.StringToBSTR(string_aux).ToPointer();
  IntPtr ab = new IntPtr(pt);
  return ab;
}

public void GetValue()  
{

   SendMessageW(utilityHandle1, TVM_GETITEMHEIGHT, handle,Testing());

}

--------------------- C++ code --------------

CString *st = (CString*)lParam;

MessageBox(NULL,*st,L"stringvalue",NULL);

Here *st value is empty.

0

1 Answer 1

3

You seem to be abusing TVM_GETITEMHEIGHT. Why not use a custom message.

CString is a C++ class. It is not binary compatible with a BSTR.

Personally I would use Marshal.StringToCoTaskMemUni in the C# and cast to wchar_t* in the C++. Remember to destroy the unmanaged memory after you've used it when SendMessageW returns, by calling Marshal.FreeCoTaskMem.

Sign up to request clarification or add additional context in comments.

6 Comments

I am sending custom message in place of TVM_GETITEMHEIGHT. I am new to c++ I have used Marshal.StringToUni in c# but I do not know how to convert 'LPARAM' to 'wchar_t*' and to 'CString' Can you please tell c++ code to covert 'LPARAM' to 'CString'
You do know how to do this. You have the code in your answer. Cast the lParam to wchar_t*. With (wchar_t*)lParam. Or reinterpret_cast<wchar_t*>)(lParam). You don't need a CString to call MessageBoxW.
He should be able to use CString s = (const wchar_t*)lParam;? though it is not necessary unless you need to do some string formatting with CString
I have tried those three but message in MessageBox is coming as empty.c# code is 'IntPtr bn = Marshal.StringToCoTaskMemUni("passingstring");' --- 'SendMessageW(utilityHandle, Win32Utilities.RegisterWindowMessage("requiredcontrol"), handle,bn )' ---Marshal.FreeCoTaskMem(bn);-----In C++: wchar_t* cvb = reinterpret_cast<wchar_t*>(lParam); ----- MessageBox(NULL,cvb,L"stringvalue",NULL); ------ here cvb value is empty. Am I missing anything here ?
And you changed the C# code to call StringToCoTaskMemUni?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.