gpt4 book ai didi

c++ - 为什么我可以在没有调用 CoInitializeEx 的情况下调用 StringFromCLSID?

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:35:47 32 4
gpt4 key购买 nike

我正在通过 C++ 学习 COM。来自 MSDN :

Applications are required to use CoInitializeEx before they make any other COM library calls except for memory allocation functions.

内存分配函数在我看来是CoTaskMemAllocCoTaskMemFree

但我明白了,无论是否调用 CoInitializeExCoUninitialize 函数,我的“Hello World”都能正常工作。在我的代码中,我使用了在 combaseapi.h header 中声明的 StringFromCLSID 函数。所以,在我看来它是一个 COM 函数。我的代码:

/* entry_point.cpp */
#include "Tools.h"
#include <objbase.h>

int main(){
HRESULT hr = ::CoInitializeEx(nullptr, COINIT_MULTITHREADED);
if (FAILED(hr)){
trace("Can't initialize COM for using in the current thread.");
keep_window_opened();
return 1;
}
// {D434CF7D-2CDD-457A-A4EF-5822D629CE83}
static const CLSID clsid =
{ 0xd434cf7d, 0x2cdd, 0x457a, {
0xa4, 0xef, 0x58, 0x22, 0xd6, 0x29, 0xce, 0x83 } };

const size_t SIZE = 39;
wchar_t* wch = nullptr;
hr = ::StringFromCLSID(clsid, &wch);
if (FAILED(hr)){
trace("Can't convert CLSID to wchar_t array.");
}
else{
trace("CLSID converted to wchar_t array.");
char mch[SIZE];
size_t count = 0;
int result = ::wcstombs_s(&count, mch, wch, SIZE);
if (result){
trace("Can't convert wchar_t array to char array.");
}
else{
trace(mch);
}
::CoTaskMemFree(wch);
}
::CoUninitialize();

keep_window_opened();
return 0;
}

如果我删除 CoInitializeExCoUninitialize 函数的调用,那么我的代码仍然有效。我预计它不会工作......

为什么 StringFromCLSID 即使之前没有调用 CoInitializeEx 也能工作?

谢谢。

最佳答案

StringFromCLSID 基本上是将 GUID 值(字节)打印成字符串,然后用连字符和大括号很好地格式化它。不涉及任何其他内容,因此调用成功并不真正需要 COM 初始化。

为了安全起见,您必须执行 CoInitialize/CoInitializeEx,但不这样做不一定会立即遇到问题。

关于c++ - 为什么我可以在没有调用 CoInitializeEx 的情况下调用 StringFromCLSID?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30502362/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com