On Sat, Oct 18, 2025 at 5:57 PM LIU Hao <[email protected]> wrote:
>
> This caused `ConvertBSTRToString()` to fail, but it didn't return a null 
> pointer:
>
>      E:\lh_mouse\Desktop>cl /nologo /W4 /O2 /EHs test.cc /link vccomsup.lib
>      test.cc
>
>      E:\lh_mouse\Desktop>test.exe
>             b1  = 02FED020
>      exception  = bad allocation
>
>
> Maybe we can just do `str = new char[mbSize];`. The exception will propagate 
> to the caller.
>

It seems that the behavior depends on the library being linked. When
linking with vccomsup.lib, std::bad_alloc propagates to the caller.
However, when linking with comsuppw.lib as suggested in
<https://learn.microsoft.com/en-us/cpp/cpp/convertbstrtostring?view=msvc-170>,
_com_error will be raised.


     #include <comutil.h>
     #include <comdef.h>
     #include <string.h>
     #include <wchar.h>
     #include <stdio.h>
     #include <new>

     int
     main(void)
       try {
         constexpr unsigned int len = 0x30000000;

         ::BSTR b1 = new wchar_t[len + 1];
         ::wmemset(b1, L'a', len);
         b1[len] = 0;
         ::printf("       b1  = %p\n", b1);

         char* s1 = ::_com_util::ConvertBSTRToString(b1);
         ::printf("       s1  = %p\n", s1);
         ::printf("strlen(s1) = %zd (expecting %d)\n", ::strlen(s1), len);

         delete[] b1;
         delete[] s1;
       }
       catch(::std::exception& e) {
         ::printf("exception  = %s\n", e.what());
       } catch (::_com_error& e) {
         ::printf("com error = %s\n", e.ErrorMessage());
       }


C:\msys64\home\yanjie>cl /nologo /W4 /O2 /EHs Test3.cpp /link comsuppw.lib
Test3.cpp

C:\msys64\home\yanjie>Test3.exe
       b1  = 01028020
com error = Not enough memory resources are available to complete this
operation.


_______________________________________________
Mingw-w64-public mailing list
[email protected]
https://lists.sourceforge.net/lists/listinfo/mingw-w64-public

Reply via email to