一个关于ATL Connection Point机制中COM接口类型转换的问题
在研究ATL Connection Point机制中发现一个问题,想不明白为什么,想大家请教。
首先看一个简单程序,这个程序编译能够通过,链接不能通过
struct A
{
int Send();
};
class B
{
public:
int Send() { cout<<"This is B::Send()!"<<endl; };
};
int main(void)
{
B *pB = new B;
A *pA = reinterpret_cast<A*>(pB);
pA->Send();
delete pB;
return 0;
}
VC会报告:
error LNK2019: unresolved external symbol "public: int __thiscall A::Send(void)" (?Send@A@@QAEHPAH@Z) referenced in function _main
但是,如果将struct A定义为一个接口IA,创建一个ATL工程,比如名为ConnectionTest,定义接口IA,IDL文件如下所示:
library ConnectionTestLib
{
importlib("stdole2.tlb");
[
object,
uuid(21D953A8-1314-425A-943A-ABFD7D849948),
helpstring("IA Interface"),
pointer_default(unique)
]
interface IA : IUnknown{
[helpstring("method Send")] HRESULT Send(void);
};
// 此处我删除了coclass因为不需要
};
编译这个ATL工程,然后修改main函数如下:
#include <iostream>
#define STD_IMPORT_OPTIONS raw_interfaces_only, raw_native_types, no_namespace, named_guids
#import "ConnectionTest.tlb" STD_IMPORT_SETTINGS
using namespace std;
class B
{
public:
int Send() { cout<<"This is B::Send()!"<<endl; };
};
int main(void)
{
B *pB = new B;
IA *pIOC = reinterpret_cast<IA*>(pB);
pIOC->Send();
delete pB;
return 0;
}
这个程序当然无法运行,但是,它能通过编译和链接,build成功。
我觉得这是件很奇怪的事。struct A和interface IA有什么区别?为什么编译器会区别对待?
同样是类型转换之后的函数调用,为什么会一个成功,一个失败?
多谢了。