日期:2014-05-17  浏览次数:20855 次

C#调用COM组件,可以创建对象,但是调用函数的时候抛出异常了.
本帖最后由 u011893584 于 2013-09-02 22:43:57 编辑
我有下面这个小C#程序,调用一个名字叫Sample4的com组件,组件的对象是Fun,接口名IFun,函数Add。
C#的项目视图,选中项目中引入的dll,鼠标右键,选择属性,把“嵌入互操作类型”设置为False

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Sample4Lib;
namespace UseCom
{
    class Program
    {
        static void Main(string[] args)
        {
            //Fun pf = new Fun();//OK now
            IFun pf = new Fun();
            var a = pf.Add(2, 3);
            IFun f1 = pf as IFun;
        }
    }
}

调用的时候,new Fun()这句没有问题,而var a=pf.Add这句出问题了。如下图所示。

我的这个com组件是VC实现的,主要代码如下:
idl文件内容:

[
object,
uuid(906AA3B5-7341-455F-B391-AD6D15087701),
pointer_default(unique)
]
interface IFun : IUnknown{
[] HRESULT Add([in] LONG n1, [in] LONG n2, [out,retval] LONG** pVal);
};
[
uuid(197CE716-F985-4C7A-B202-7FFB27E6B3A0),
version(1.0),
]

Fun.cpp中的函数实现:

STDMETHODIMP CFun::Add(LONG n1, LONG n2, LONG** pVal)
{
// TODO: Add your implementation code here
*pVal=new LONG;
**pVal=n1+n2;
return S_OK;
}

这个com组件用一个VC写的客户段调用是没有问题的,能运行。但是用我写的C#程序来调用就不行。如果我把Add函数的返回值类型改为LONG* pVal,不改变指针本身,那么VC客户端经过小修改也能运行,而我的C#调用程序还是会遇到同样的问题。
这到底是为什么呢?

还请指教!

------解决方案--------------------
你的C代码不全,没看到你FuncClass怎么继承的IFun。
------解决方案--------------------