高分征解COM入门问题!(100分)

  • 主题发起人 主题发起人 EdwardZhou
  • 开始时间 开始时间
E

EdwardZhou

Unregistered / Unconfirmed
GUEST, unregistred user!
下面的代码是我从一本书上copy的,并且dll已经用Run项目的Register ActiveX Server注册了,可是

CoCreateInstance老是出错并显示fail对话框!并且在调用中也出现了内存违规访问,为什么?

dll部分的Unit1文件(GUID自动生成):
unit Unit1;

{$WARN SYMBOL_PLATFORM OFF}

interface

uses
Windows, ActiveX, Classes, ComObj;

type
ICalculator = interface
['{F72C1C14-A0A7-46DB-A5B4-26D14E54A4D4}']
function Add(x,y:integer):Integer;stdcall;
function Mult(x,y:integer):Integer;stdcall;
end;

TCalculator = class(TComObject,ICalculator)
protected
function Add(x,y:integer):Integer;stdcall;
function Mult(x,y:integer):Integer;stdcall;
end;

const
Class_Calculator: TGUID = '{67B5C191-74FA-4960-A313-3134E4F01C29}';

implementation

uses ComServ;

function TCalculator.Add(x,y:integer):Integer;
begin
Result := x + y;
end;

function TCalculator.Mult(x,y:integer):Integer;
begin
Result := x * y;
end;

initialization
TComObjectFactory.Create(ComServer, TCalculator, Class_Calculator,
'Calculator', '', ciMultiInstance, tmSingle);

end.

Client部分的Unit文件:
unit Unit1;

interface

uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ActiveX;

type
ICalculator = interface
['{F72C1C14-A0A7-46DB-A5B4-26D14E54A4D4}']
function Add(x,y:integer):Integer;stdcall;
function Mult(x,y:integer):Integer;stdcall;
end;

TForm1 = class(TForm)
Button1: TButton;
Edit1: TEdit;
Edit2: TEdit;
Edit3: TEdit;
Edit4: TEdit;
procedure FormCreate(Sender: TObject);
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
Fcal : ICalculator;
public
{ Public declarations }
end;

const
Class_Calculator: TGUID = '{67B5C191-74FA-4960-A313-3134E4F01C29}';

var
Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.FormCreate(Sender: TObject);
var hRet : HResult;
begin
hRet := CoCreateInstance(Class_Calculator,nil,
CLSCTX_INPROC_SERVER,ICalculator,Fcal);
if hRet = S_OK then
MessageBox(0,'success!','',MB_OK)
else
MessageBox(0,'fail!','',MB_OK)
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
Edit3.Text := IntToStr(
Fcal.Add(StrToInt(Edit1.Text),StrToInt(Edit2.Text))
);
Edit4.Text := IntToStr(
Fcal.Mult(StrToInt(Edit1.Text),StrToInt(Edit2.Text))
);
end;

end.
 
//////////////////单元文件最后'end.'前加上以下的初始化
initialization
oleinitialize(nil);
finalization
oleuninitialize;
 
问题解决,能不能说说为什么?
 

Similar threads

I
回复
0
查看
762
import
I
I
回复
0
查看
771
import
I
I
回复
0
查看
569
import
I
后退
顶部