While working on com interop ,i followed the tutorial on this link.The code runs fine as i have done some modification depending on my requirement but the problem comes while dealing with the string.I am using BSTR string here as a perimeter here. Here is the function in c# that i am calling from c++
public string ShowDialog([MarshalAs(UnmanagedType.BStr)] string stringToPrint)
{
// Console.WriteLine(" Enter TOTP input:");
// stringToPrint = Console.ReadLine();
if (stringToPrint == "111111")
{
MessageBox.Show("true");
}
else
{
MessageBox.Show("false");
}
return stringToPrint;
}
here is my C++ main function section of the code where the calls are being made
CoInitialize(NULL);
MyInterop::IMyDotNetInterfacePtr pDotNetCOMPtr;
HRESULT hRes = pDotNetCOMPtr.CreateInstance(MyInterop::CLSID_MyDotNetClass);
if (hRes == S_OK)
{
BSTR lResult ;
cout << "enter TOTP input" << endl;
_bstr_t bstrStatus = SysAllocString(L"111111");
pDotNetCOMPtr->ShowDialog(bstrStatus,&lResult);
SysFreeString(bstrStatus);
}
CoUninitialize();
system("pause");
The issues that i am facing are as follows:
- BSTR string is not being returned on the console after it is passed from c++ code although i am using a returning function in c#
- Is it possible to insert input dynamically on the console as i am using SysAllocString("") here which makes it somewhat hard coded.

When you're using Visual Studio and the #import directive, the generated code uses _bstr_t which is a smart wrapper class over BSTR (the raw Windows type).
So, you don't have to use SysAllocString nor SysFreeString, you can just use _bstr_t very naturally. For example, in your case, if your C# method signature is like this:
then you can use a C++ code like this:
You could also directly write this:
// or this (with automatic ansi to unicode conversion)
All _bstr_t are automatically allocated and freed.