delphi 创建DLL文件 及其调用和注意事项


本文整理自网络,侵删。

 首先创建一个DLL文件,项目自带的代码为:


library ProjectPnr;
 
{ 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
  SysUtils,
  Classes,
 
//再在Uses下声明一个函数:
function Add(a, b: integer):integer; // 函数功能 实现a,b相加
begin
   result := a + b;  
endexports add;  // 必须要有这句才能输出
 
begin
end.
 这样一个简单的dll就创建成功了,保存为test,建议最好把建好的dll放在和调用项目放在一起,

 接下来就是调用了,调用很简单:

新建一个application,在implementation上面引用刚刚写的dll函数:

function apnr(a,b: integer):integer; external 'test.dll';
 这里注意,大小写要和dll里的函数一样。

放一个按钮,在OnClick事件中调用dll里函数就行。


procedure TForm2.Button1Click(Sender: TObject);
begin
 ShowMessage(add(1, 2));     //3
end;
但是当返回值是string时,调用会报指针内存错误,比如说:(至少在delphi7里)


//dll里函数
function add(a, b: integer): string;
begin
  result := IntToStr(a + b);
end;
解决方法:

将返回值string改成PChar,就可以调用了,应该是dll的处理string和application处理string的方法不一样吧。

然后我将用XE打开刚刚调用dll的项目,发现直接闪退,我在用D7打开这个项目,结果有返回值,

这种现象是因为D7的PChar长度是单字节,而XE的PChar长度是双字节,具体用SizeOf测试,D7用的是Ansi编码,XE用的时Unicode编码,

解决方法

把PChar改成PAnsiChar或PWideChar。

为了兼容,最好把dll要返回的string变成PAnsiChar。

相关阅读 >>

Delphi做异型窗体png透明

Delphi 无法打不开读取文件名有逗号的文件

Delphi中的处理事件 application.processmessages

Delphi listview 实现进度条显示

Delphi xe5 android获取手机联系人,并用listview显示

Delphi 苹果系统弹出链接

Delphi colorbox不需要系统那么多颜色,只想自定义显示其中几个,怎么做?

Delphi 列出所有可视窗口

Delphi 获取中文/数字星期的函数

Delphi 根据经纬度计算地球上两点之间的距离

更多相关阅读请进入《Delphi》频道 >>



打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...