我正在学习 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。
这是我的数学函数库
#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/