C++中的Object equivalent

m3eecexj  于 11个月前  发布在  其他
关注(0)|答案(2)|浏览(86)

我在这个论坛和互联网上读过很多类似的主题,但我没有找到解决我问题的方法。
我只是想把VB中的代码转换成C++:

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

字符串
可以用C++翻译吗?

ou6hu8tu

ou6hu8tu1#

看一下CoCreateInstance,在调用CocketInstance之前,不要忘记调用CLSIDFromProgID和CoInitialize。

nx7onnlm

nx7onnlm2#

首先,添加所需的头文件。请注意,atlmfc库需要从Visual Studio安装。

// 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创建Dispatcher:

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);

相关问题