COM互操作中BSTR字符串传递及动态输入问题问询
Hey there, let's work through your two COM interop issues step by step:
Looking at your C# code, the reason you don't see the incoming string from C++ is that you don't have any code that outputs it! The Console.WriteLine line is commented out, and there's no other statement that prints the stringToPrint parameter.
Here's a fixed version of your C# method that will show the received input:
public string ShowDialog([MarshalAs(UnmanagedType.BStr)] string stringToPrint) { // Print the incoming string from C++ to the console Console.WriteLine($"Received input from C++: {stringToPrint}"); if (stringToPrint == "111111") { MessageBox.Show("true"); } else { MessageBox.Show("false"); } return stringToPrint; }
Also, a quick note on your C++ code: since you're using _bstr_t, it automatically manages the underlying BSTR memory, so you don't need to call SysFreeString(bstrStatus) manually—this avoids potential double-free issues.
Instead of hardcoding the string with SysAllocString, you can read input from the console as a wide string (since BSTR uses UTF-16 wide characters) and convert it to a BSTR easily. Here's how to modify your C++ code:
CoInitialize(NULL); MyInterop::IMyDotNetInterfacePtr pDotNetCOMPtr; HRESULT hRes = pDotNetCOMPtr.CreateInstance(MyInterop::CLSID_MyDotNetClass); if (hRes == S_OK) { BSTR lResult = nullptr; cout << "enter TOTP input" << endl; // Read wide string input from the console std::wstring userInput; std::getline(std::wcin, userInput); // Convert std::wstring to BSTR using _bstr_t (auto-manages memory) _bstr_t bstrStatus(userInput.c_str()); pDotNetCOMPtr->ShowDialog(bstrStatus, &lResult); // Optional: Print the returned string from C# if (lResult != nullptr) { wcout << L"String returned from C#: " << lResult << endl; SysFreeString(lResult); // Always free the BSTR returned by COM! } } CoUninitialize(); system("pause");
Key points here:
- We use
std::wcinandstd::wstringto handle wide characters, which matches BSTR's UTF-16 encoding perfectly. _bstr_ttakes care of allocating and freeing the BSTR for us, so we don't have to deal withSysAllocString/SysFreeStringdirectly.- Don't forget to call
SysFreeString(lResult)! COM conventions state that the caller is responsible for freeing any BSTR returned by a method.
内容的提问来源于stack exchange,提问作者Shahnawaz Khan Niazi

