首先创建一个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;
end exports 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。

最新文章

  1. thinkphp连接数据库
  2. Swift3.0基础语法学习<三>
  3. QML定时器
  4. Hibernate学习
  5. java提高篇(八)-----实现多重继承
  6. Android的状态栏通知(Notification)
  7. java 文件读和写(整理)
  8. php学习笔记upset函数。
  9. PCB泪滴设计
  10. 树形结构模型Django-MPTT
  11. Java多线程01(Thread类、线程创建、线程池)
  12. 使用Visual Studio Team Services敏捷规划和项目组合管理(六)——VSTS仪表盘的使用
  13. 【转】实习小记-python 内置函数__eq__函数引发的探索
  14. 记一次spring boot参数初始化的问题
  15. Matlab的用法总结
  16. Kylin工作原理、体系架构
  17. pycharm中导入requests,xmlx等模块的方法。
  18. Vue.js路由
  19. 【NGINX】Windows配置
  20. Flask初级(十一)flash与APScheduler 实现定时任务

热门文章

  1. centos7 & ubuntu14.02安装sublime 3
  2. POJ2142(扩展欧几里得)
  3. mysql实战优化之八:关联查询优化
  4. C# 32位程序访问64位注册表
  5. IO模型比较分析
  6. CVE-2017-11882复现配合koadic
  7. python's seventeenth day for me 面向对象
  8. re模块练习
  9. HADOOP的API简单介绍
  10. 「小程序JAVA实战」微信小程序工程结构了解(五)