调用DLL的问题
小弟最近学习delphi中调用DLL,遇到一个问题:调用一个颜色对话框7次后出现如下错误"Project TestProject.exe raised exception class EAccessViolation with message 'Access violation at address 00383104' in module 'ColorProject.dll'.Read of address 69207021'.Process Stopped.Use Step or Run to continue."
下面贴出代码:
ColorUnit.pas:
unit ColorUnit;
interface
uses Windows, Messages,SysUtils,Variants,Classes,Graphics,Controls,Forms,Dialogs,StdCtrls;
function ColorValue():string;stdcall;
implementation
function ColorValue():string;stdcall;
var ColorDialog1:TColorDialog;
begin
ColorDialog1:=TColorDialog.Create(nil);
ColorDialog1.Execute;
ColorDialog1.Options:=ColorDialog1.Options+[cdAnyColor];
result:='$'+InttoHex(ColorDialog1.Color,6);
showmessage('$'+InttoHex(ColorDialog1.Color,6));
ColorDialog1.Destroy;
end;
end.
--------------------
ColorProject.dpr
library ColorProject;
{ Important note about DLL memory management: ShareMem must be the
first unit in your library's USES clause AND your project's (select
Project-View Source) USES clause if your DLL exports any procedures or
functions that pass strings as parameters or function results. This
applies to all strings passed to and from your DLL--even those that
are nested in records and classes. ShareMem is the interface unit to
the BORLNDMM.DLL shared memory manager, which must be deployed along
with your DLL. To avoid using BORLNDMM.DLL, pass string information
using PChar or ShortString parameters. }
uses
Windows,Messages,SysUtils,Variants,Classes,Graphics,Controls,Forms,Dialogs,StdCtrls,ColorUnit in 'ColorUnit.pas';
{$R *.res}
exports ColorValue;
begin
end.
----------------------------------------
TestUnit.pas
unit TestUnit;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
TForm1 = class(TForm)
Button1: TButton;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
function ColorValue():string;stdcall;
External 'ColorProject.dll';
{$R *.dfm}
procedure TForm1.Button1Click(Sender: TObject);
begin
ColorValue();
end;
end.
希望各位指点迷津啊。。。。。
[解决办法]
dll里的函数参数或返回类型都不要用string,换pchar
要么在uses第一个加上sharemem
[解决办法]
- Delphi(Pascal) code
{ Important note about DLL memory management: ShareMem must be the first unit in your library's USES clause AND your project's (select Project-View Source) USES clause if your DLL exports any procedures or functions that pass strings as parameters or function results. This applies to all strings passed to and from your DLL--even those that are nested in records and classes. ShareMem is the interface unit to the BORLNDMM.DLL shared memory manager, which must be deployed along with your DLL. To avoid using BORLNDMM.DLL, pass string information using PChar or ShortString parameters. }
[解决办法]
简单点
dll和exe工程最先引用ShareMem
- Delphi(Pascal) code
uses ShareMem, Windows,Messages,SysUtils...