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

C#不能创建一个已注册的com对象,为什么?
我用VS2008,建立一个工程ATLProject1,里面先有一个VC建立的ATL工程,有一个组件叫做Fun,接口叫做IFun,函数叫做Add([in] int n1,[in] int n2,[out,retval] int* pVal). 编译成功,自动注册。

然后我建立一个C#的工程,敲入以下代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ATLProject1Lib;
namespace cs_ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            IFun f = new FunClass();
            Console.WriteLine(f.Add(2, 3));
        }
    }
}

运行调试到了IFun f=new FunClass();这一句出错了,如下:
Additional information: Retrieving the COM class factory for component with CLSID {6FB1F141-A978-420B-892B-6DB29610F314} failed due to the following error: 80040154.

'cs_ConsoleApplication1.vshost.exe' (Managed): Loaded 'C:\WINDOWS\assembly\GAC_MSIL\System.Configuration\2.0.0.0__b03f5f7f11d50a3a\System.Configuration.dll'
The program '[520] cs_ConsoleApplication1.vshost.exe: Managed' has exited with code 0 (0x0).

我把这句改成了这样也不行:

            IFun f = new Fun();

这是为什么呢?

------解决方案--------------------
你重新添加下com引用看看。
------解决方案--------------------
估计你的C#程序是64位的。你有COM组件源代码的话,编译一个32位版本,一个64位版本,然后注册到对应的注册表位置里面去。
------解决方案--------------------
试试下面的方法:
1.在编译你的dll时,将其定义为com组件;
2.生产dll之前,对程序集进行签名(Choose a strong name key 下选择new,写入自己的key file name)
3.生成dll
4.注册dll
  a.以管理员运行cmd,转到你的RegAsm.exe所在的.net 框架文件夹,并运行如下命令,如:我的.net 框架在(C:\Windows\Microsoft.NET\Framework64\v2.0.50727)——(dll路径:C:\xx\xx.dll),如下: