#import从.NET DLL生成的Tlb的神秘错误

经常看到有朋友问到类似的问题,问题本身不复杂,但是答案不是特别明显,这里我把解决方法Post出来和大家共享一下,希望能够有所帮助。<?xml:namespace prefix = o />

假设我们有下面的A.cs文件:

using System;

using System.Runtime.InteropServices;

[InterfaceType(ComInterfaceType.InterfaceIsDual)]

public interface IA

{

Type Func();

}

[ComVisible(true)]

public class A : IA

{

public Type Func()

{

return null;

}

}

首先用CSC.exe编译为DLL文件,然后用TlbExp.exe生成对应的TLB (TypeLibrary)让下面的C++代码来引用之:

#import "a.tlb" no_namespace

void main(void)

{

//

// use class A...

//

}

但是使用CL.exe编译的时候发生了如下错误:

Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 15.00.21022.08 for 80x86

Copyright (C) Microsoft Corporation. All rights reserved.

t.cpp

d:\var\a.tlh(49) : error C2146: syntax error : missing ';' before identifier 'Fu

nc'

d:\var\a.tlh(49) : error C4430: missing type specifier - int assumed. Note: C++

does not support default-int

d:\var\a.tlh(49) : error C4430: missing type specifier - int assumed. Note: C++

does not support default-int

d:\var\a.tlh(49) : warning C4183: 'Func': missing return type; assumed to be a m

ember function returning 'int'

d:\var\a.tli(14) : error C2143: syntax error : missing ';' before 'IA::Func'

d:\var\a.tli(14) : error C2433: '_TypePtr' : 'inline' not permitted on data decl

arations

d:\var\a.tli(14) : error C4430: missing type specifier - int assumed. Note: C++

does not support default-int

d:\var\a.tli(14) : error C4430: missing type specifier - int assumed. Note: C++

does not support default-int

d:\var\a.tli(18) : error C2064: term does not evaluate to a function taking 2 ar

guments

错误发生在VC生成A.TLB对应的头文件(*.tlh)和实现文件(*.tli)中,这难道是VCBug

实际上答案很简单,这是因为A.TLB引用了mscorlib.tlb造成的。Mscorlib.NET Framework中的类型所对应的Type Library,常见的.NET类型基本上都包括在里面了。#import并没有能够自动处理这种引用关系,并自动#import mscorlib.tlb。因此,编译器抱怨无法找到.NET中的对应类型,这里出错的类型是_TypePtr,是_Type接口(对应Type类型)的智能指针类型。这个步骤需要你自己做。因此正确的代码如下:

// add this line

#import "mscorlib.tlb" no_namespace

#import "a.tlb" no_namespace

void main(void)

{

//

// use class A...

//

}

作者: 张羿(ATField)
Blog: http://blog.csdn.net/atfield
http://blogs.msdn.com/yizhang
转载请注明出处

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值