我使用VS2005制作了一个简单的C#DLL(这是一个更大的项目的一部分)。我需要通过VBA代码在Excel中使用DLL,所以我在程序集上使用COM Interop。我尝试使构建过程自动生成必要的TLB文件,这样我就不需要在每次构建后都转到命令行并使用regasm。
我的问题是虽然DLL编译和构建正常,但它不会生成TLB文件。相反,标题中的错误会在输出框中打印出来。
我已经通过转到VS2005中的项目属性来获取其他DLL来构建TLB文件 - >构建 - >输出 - >检查“注册COM互操作”。另外,我在AssemblyInfo.cs 中有 [assembly:ComVisible(true)]。
以下是问题DLL的源代码摘要以及它为返回类型引用的DLL:
using System;
using System.IO;
using System.Runtime.InteropServices;
using SymbolTable;
namespace ProblemLibrary
{
public class Foo
{
public Foo(string filename)
{
...
}
// method to read a text file into a SymbolTable
public SymbolTable BuildDataSet(string[] selected)
{
...
}
}
}
以下是SymbolTable.dll的摘要。它包含ProblemLibrary使用的返回类型。
using System;
using System.Collections.Generic;
namespace SymbolTable
{
public class SymbolTable
{
readonly Dictionary<SymbolInfoStub, string> _symbols = new Dictionary<SymbolInfoStub, string>();
/*methods that interact with Dictionary snipped*/
}
}
答案 0 :(得分:21)
确保您在装配级别拥有GuidAttribute。
[Guid("<PUT-GUID-HERE-1>")]
[ComVisible(true)]
interface IFoo
{
void DoFoo();
}
[Guid("<PUT-GUID-HERE-2>")]
[ComVisible(true)]
[ProgId("ProgId.Foo")]
class Foo : IFoo
{
public void DoFoo()
{
}
}
答案 1 :(得分:3)
我看到了类似的问题。我得到了一个错误:
警告MSB3391:不包含任何内容 可以取消注册COM的类型 互操作。
我遵守了所有规则(ComVisible等)但没有任何效果。
解决方案:我必须在默认构造函数中添加一些内容,以便它不会被优化掉。当我在那里有一些东西时,注册完成没有消息,组件在注册表中可见。
有趣的说明:我的一个朋友设法在他的机器上使用空的默认构造函数注册原始DLL(64位Windows-7,VS2008-Professional,就像我的一样)。但是,他的REGASM.EXE是:
C:\的Windows \ Microsoft.NET \ Framework64 \ V2.0.50727 \ regasm.exe
我的是:
C:\的Windows \ Microsoft.NET \ Framework64 \ v4.0.30319 \ RegAsm.exe
因此,.NET框架版本之间可能存在一些差异 - 可能后期版本的优化程度太高而REGASM没有考虑到这一点。
答案 2 :(得分:1)
在AssemblyInfo.cs文件中,请确保您具有以下内容:
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(true)]
<强>更新强>
阅读:How can I make use of .NET objects from within Excel VBA?