c++ - 如何在 native Visual C++ 中轻松使用 COM 组件

标签 c++ visual-c++ com activex

我正在尝试构建一个使用 VisualStudio ´05 中的 COM 组件的应用程序 在 native C++ 中。 MSDN 中对事物的 native 和托管描述的混合完全破坏了我的 脑。 (我认为 MSDN 在这方面一团糟) 我需要一个简短的 native C++ 代码示例来加载我的组件 并使其可用。 我同意编译器创建包装器等。

请不要建议我使用基于对话框的 MFC 示例,因为 它不适用于此组件,它本身就是一个巨大的 一堆 c...代码。

这会是 native com 与托管 com 的问题吗?

我完全迷路了,请给我一些方位……

编辑:感谢所有帮助。 我的问题是我只有一个注册的 dll(实际上是 OCX,见下文) .我(个人)知道 界面应该是什么样子,但我该如何告诉我的程序? 没有定义的 header 我可以使用的接口(interface) ID。但我读到 c++ 编译器 可以帮我提取包起来。有人知道这是怎么做到的吗?

澄清:我只有 OCX 和文档中的线索 组件,它应该公开哪些方法。

最佳答案

来 self 的博客文章的完整示例(正是您所需要的):How to Call COM Object from Visual Studio C++?

// https://helloacm.com/how-to-call-com-object-from-visual-studio-c/
#include <iostream>
#include <objbase.h>
#include <unknwn.h>
#include <Propvarutil.h>
#import "wshom.ocx" no_namespace, raw_interfaces_only  

using namespace std;

int main() {
    HRESULT hr;
    CLSID clsid;
    CoInitializeEx(nullptr, COINIT_MULTITHREADED);  
    CLSIDFromProgID(OLESTR("WScript.Shell"), &clsid);   
    IWshShell *pApp = nullptr;
    hr = CoCreateInstance(clsid, nullptr, CLSCTX_INPROC_SERVER, __uuidof(IWshShell), reinterpret_cast<LPVOID *>(&pApp));
    if (FAILED(hr) || pApp == nullptr) {
        throw "Cannot Create COM Object";
    }
    int out;
    VARIANT s;
    InitVariantFromInt32(0, &s);
    VARIANT title;
    InitVariantFromString(PCWSTR(L"title"), &title);
    VARIANT type;
    InitVariantFromInt32(4096, &type);
    BSTR msg = ::SysAllocString(L"Hello from https://helloacm.com");
    pApp->Popup(msg, &s, &title, &type, &out);
    CoUninitialize();
    cout << "Out = " << out;
    return 0;
}

关于c++ - 如何在 native Visual C++ 中轻松使用 COM 组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1145768/

相关文章:

c++ - 在超出范围时停止 std::vector 调用 d'tors

c++ - 在 visual studio 2015 community c++ 中,如何修复警告 C4838 : conversion from 'unsigned int' to 'int' requires a narrowing conversion

com - 如何解决调用::UuidToString() 时出现的链接错误?

c++ - 如何修改unordered_map中的值?

c# - 我需要做什么才能在 C# 中实现 "out of proc"COM 服务器?

c# - 创建和注册 COM 服务器对象 .NET

c++ - SDL2 中的多个显示

c++ - C++ 测试用例的基本字符串差异

windows - 在 WSPSend 中获取目标端口

c++ - VS 2010 中的复数问题