C++ 中的 CreateObject 等效项

问题描述 投票:0回答:2

早上好。我在这个论坛和互联网上阅读了很多类似的主题,但我没有找到解决我的问题的方法。

我只是想在 C++ 中转换此 VB 行:

Dim OR As Object
Dim info as String
OR = CreateObject("ORIG.API")
info = OR.info()

你能告诉我c++的翻译吗?

c++ vb.net api com createobject
2个回答
2
投票

看看CoCreateInstance。在调用 CoCreateInstance 之前不要忘记调用 CLSIDFromProgID 和 CoInitialize。


0
投票

首先,添加所需的标头。请注意,需要从 Visual Studio 安装程序安装

atlmfc
库:

// cl /Zi /Od /DEBUG:FULL -IE:\VisualStudio\2022\BuildTools\VC\Tools\MSVC\14.16.27023\atlmfc\lib\x86 -IE:\VisualStudio\2022\BuildTools\VC\Tools\MSVC\14.38.33130\atlmfc\include /EHsc .\test.cpp /link /libpath:"E:\VisualStudio\2022\BuildTools\VC\Tools\MSVC\14.16.27023\atlmfc\lib\x86" atls.lib /DEBUG:FULL ; .\test.exe
#pragma comment(lib, "Ole32.lib")
#include <Windows.h>
#include <objbase.h>
#include <combaseapi.h>
#include <comdef.h>
#include <atlbase.h>

然后,在通话前后使用 CoInitializeCoUninitialize

int main() {
    CoInitialize(NULL);
    
    // Your code here    

    CoUninitialize();
}

然后,使用 CLSIDFromProgID 获取对象,并将其存储在

clsid
:

HRESULT hr;
CLSID clsid;
hr = CLSIDFromProgID(L"ORIG.API", &clsid);

然后,使用 CoCreateInstance 创建一个调度程序:

IDispatch *pOR;
hr = CoCreateInstance(clsid, NULL, CLSCTX_INPROC_SERVER, IID_IDispatch, (void **)&pOR);

然后,使用 IDispatch::GetIDsOfNames:

获取您需要的方法
DISPID PropertyID[1] = {0};
BSTR PropName[1];
PropName[0] = SysAllocString(L"info");
hr = pOR->GetIDsOfNames(IID_NULL, PropName, 1, LOCALE_USER_DEFAULT, PropertyID);

最后,使用 IDispatch::Invoke 调用它。这里我展示了如何传递2个字符串参数,你可以根据你的需要修改它们:

DISPPARAMS dp = {NULL, NULL, 0, 0};
VARIANT vResult;
EXCEPINFO ei;
UINT uArgErr;

// Allocate memory for the arguments array
dp.rgvarg = new VARIANT[2];
if (dp.rgvarg == NULL)
    return E_OUTOFMEMORY;

// Set the number of arguments
dp.cArgs = 2;

// Initialize the arguments as empty variants
VariantInit(&dp.rgvarg[0]);
VariantInit(&dp.rgvarg[1]);

// Set the arguments as BSTRs
BSTR account = SysAllocString(L"1234567");
BSTR pwd = SysAllocString(L"123456");
dp.rgvarg[0].vt = VT_BSTR;
dp.rgvarg[0].bstrVal = pwd;
dp.rgvarg[1].vt = VT_BSTR;
dp.rgvarg[1].bstrVal = account;

VariantInit(&vResult);

// Call the function using Invoke
hr = pOR->Invoke(PropertyID[0], IID_NULL, LOCALE_USER_DEFAULT, DISPATCH_METHOD, &dp, &vResult, &ei, &uArgErr);

// Free the memory for the arguments array
delete[] dp.rgvarg;

// Convert the BSTR to a char*
char *strResult;

strResult = _com_util::ConvertBSTRToString(vResult.bstrVal);

// Use the char* result
cout << "result: " << strResult << endl;

// Free the memory for the BSTR and the char*
delete[] strResult;
VariantClear(&vResult);
© www.soinside.com 2019 - 2024. All rights reserved.