| | 标题:delphi 中 com 实现研究手记(一) |
| 关键词:delphi com | 作者:dreamtheater | 难度:普通[] 中等[x] 高级[] |
| http://dreamtheater.yeah.net | e-mail:notexpad@163.com | 完成日期:2004年07月26日 |
| | 前言 前些日子用 delphi 写了一个 windows 外壳扩展程序,大家知道 windows 外壳扩展实际上就是 com 的一种应用 -- shell com,虽然整个程序写得还算比较顺利,但写完后还是感觉对 delphi 中 com 的实现有点雾里看花的感觉,因此我认为有必要花一点时间对 com 在 delphi 中的实现做一些研究。另外我也买了李维的新书 --《深入核心 -- vcl架构剖析》,里面有两章涉及了与 com 相关内容,看完后我知道了com 在 delphi 中的实现是基于接口(interface),而 delphi 中的接口概念又起源于对 com 的支持,总之他们之间互相影响,发展成接口在 delphi 中已经是 first-class 的地位,并且完全摆脱 com 而独立存在。 本系列文章侧重于描述 com 在 delphi 中的实现手法,主要配合 vcl 源码片断进行分析,不会涉及过多的基本概念,因此要求读者有一定的 com 和 接口概念,可以参考我在文章末尾列出的文献。本篇主要讲 com 对象在 delphi 中的创建过程。
正文 为了让读者能跟着我的分析轻松读完本篇文章,我引用文献[2]中的范例做解释,但为了更清楚地阐述问题,我改写了部分代码。所有分析请在 delphi 7 上测试。demo 源码这里下载。 在 delphi 中首先通过选择菜单 file-->new-->other...新建一个 activex library 并保存名称为 simplecomserver,再新建一个 com object,在com object wizard 中将对象命名为 simplecomobject,options 中的两个复选框都可以不必选中其他的保持默认, 现在 com服务器端的框架已经建立起来了。剩下的就是需要我们把声明的接口 isimplecomobject 的代码实现,其他的读者自己看源码吧,很简单。 | 服务器端代码 | library simplecomserver;
uses comserv, simplecomobject in 'simplecomobject.pas', simplecominterface in 'simplecominterface.pas',
exports dllgetclassobject, dllcanunloadnow, dllregisterserver, dllunregisterserver;
{$r *.res}
begin end. | unit simplecominterface;
interface uses windows; const class_simplecomobject: tguid = '{3714cf21-d272-11d3-947f-0050da73be5d}';
type isimplecomobject = interface ['{2e2a6dd0-d282-11d3-947f-0050da73be5d}'] function multiply(x, y: integer): integer; stdcall; function getclassname: widestring; stdcall; end;
implementation
end | unit simplecomobject;
interface
uses windows, activex, classes, comobj, simplecominterface;
type tsimplecomobject = class(tcomobject, isimplecomobject) protected function multiply(x, y: integer): integer; stdcall; function getclassname: widestring; stdcall; end;
const class_simplecomobject: tguid = '{3714cf21-d272-11d3-947f-0050da73be5d}';
implementation
uses comserv;
function tsimplecomobject.getclassname: widestring; begin result := tsimplecomobject.classname; end;
function tsimplecomobject.multiply(x, y: integer): integer; begin result := x * y; end;
initialization tcomobjectfactory.create(comserver, tsimplecomobject, class_simplecomobject, 'simplecomobject', 'a simple implementation of a com object', cimultiinstance, tmapartment); end. |
本文关键:Delphi 中 COM 实现研究手记(一)
本站最佳浏览方式为 分辨率 1024x768 IE 6.0(或更高版本的 IE浏览器)
|