c# - 如何使用 ComImport?

标签 c# c++ com

我正在学习 com 并将其用于基于 .net 的应用程序。

我创建了一个简单的 MathFunction dll,它有一个函数 Add 2 numbers。

然后我使用 ComImport 将其加载到 Windows 窗体应用程序中。一切正常,没有错误。当我运行该应用程序时,我得到的结果是添加 2 个数字的零。

我向函数传递了 2 个参数。

IMathFunc mathFunc = GetMathFunc();
int res = mathFunc.Add(10, 20);

现在我得到的结果是 0。这里的 IMathFunc 是 IUnkown 类型的接口(interface)。

[ComImport]
    [Guid("b473195c-5832-4c19-922b-a1703a0da098")]
    [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
    interface IMathFunc
    {
        int Add(int a, int b);
        void ThrowError();
    }

当我调试它的功能时

int Add(int a,int b)

它在“a”中显示一些大数,在“b”中显示 10。

Debug Image

这是我的数学函数库

#include<windows.h>
using namespace System;

static const GUID IID_MathFunc =
{ 0xb473195c, 0x5832, 0x4c19, { 0x92, 0x2b, 0xa1, 0x70, 0x3a, 0xd, 0xa0, 0x98 } };

struct IMathFunc:public IUnknown
{
    virtual int Add(int a, int b) = 0;

    STDMETHOD(ThrowError)() = 0;
};

namespace MathFuncLibrary {

    class MathFunc: public IMathFunc
    {
        volatile long refcount_;
    public:

        MathFunc();

        int Add(int a, int b);
        STDMETHODIMP_(ULONG) Release();

        STDMETHODIMP_(ULONG) AddRef();
        STDMETHODIMP  QueryInterface(REFIID guid, void **pObj);

        STDMETHODIMP ThrowError();

    };

}

int MathFunc::Add(int a, int b)
{
    return a + b;
}

STDMETHODIMP_(ULONG) MathFunc::Release()
{
    ULONG result = InterlockedDecrement(&refcount_);
    if(result==0)delete this;
    return result;
}

STDMETHODIMP MathFunc::QueryInterface(REFIID guid, void **pObj)
{
    if (pObj == NULL) {
        return E_POINTER;
    }
    else if (guid == IID_IUnknown) {
        *pObj = this;
        AddRef();
        return S_OK;
    }
    else if (guid == IID_MathFunc) {
        *pObj = this;
        AddRef();
        return S_OK;
    }
    else {
        // always set [out] parameter
        *pObj = NULL;
        return E_NOINTERFACE;
    }
}

STDMETHODIMP_(ULONG) MathFunc::AddRef()
{
    return InterlockedIncrement(&refcount_);
}

STDMETHODIMP MathFunc::ThrowError()
{
    return E_FAIL;
}

MathFunc::MathFunc() :refcount_(1)
{

}



extern "C" __declspec(dllexport) LPUNKNOWN __stdcall GetMathFunc()
{
    return new MathFunc();
}

我是否遗漏了导致此错误的任何内容,或者我做错了整件事......?

最佳答案

我是在 Hans Passant 的建议下得到的。

你需要改变方法

virtual int Add(int a, int b) = 0;

virtual STDMETHOD_(UINT32,Add)(int a, int b) = 0;

然后在ComImport界面

int Add(int a, int b);

 [PreserveSig]int Add(int a,int b);

关于c# - 如何使用 ComImport?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27467290/

相关文章:

c# - 解构 EF 对象会导致 Serilog 内存不足

c# - 从 XML 文件创建嵌套节点的属性列表

c++ - LoadLibrary 在 Win7 32 位上失败,在 Win XP 32 位上成功

python - 有趣的 "getElementById() takes exactly 1 argument (2 given)",有时会发生。有人可以解释一下吗?

c# - asp.net文件上传

c# - 如何禁用 gridview 中的行数据绑定(bind)事件中的按钮?

c++ - 在 C++ 中验证二进制输入

c++ - 我可以在构造函数中使用 setter 吗?

c++ - 如何为类的每个接口(interface)单独定义一些函数?

vb.net - 如何在没有 IDispatch 的情况下创建 VB.NET COM 可见接口(interface)?