You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

COM互操作中BSTR字符串传递及动态输入问题问询

Hey there, let's work through your two COM interop issues step by step:

Issue 1: Passed BSTR string not appearing in the console

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.

Issue 2: Implement dynamic console input for BSTR in C++

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::wcin and std::wstring to handle wide characters, which matches BSTR's UTF-16 encoding perfectly.
  • _bstr_t takes care of allocating and freeing the BSTR for us, so we don't have to deal with SysAllocString/SysFreeString directly.
  • 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 08:38:24