CnPack Forum


 
Subject: DLL返回动态数组
inhagk
新警察
Rank: 1



UID 40855
Digest Posts 0
Credits 12
Posts 4
点点分 12
Reading Access 10
Registered 2008-8-31
Status Offline
Post at 2009-1-9 08:13  Profile | Blog | P.M. 
DLL返回动态数组

请教大家一个问题:我的DLL返回一个动态数组怎么老是报内存错误?
Top
bahamut8348
灌水司司长
Rank: 6Rank: 6


UID 4743
Digest Posts 14
Credits 337
Posts 79
点点分 337
Reading Access 10
Registered 2007-1-18
Status Offline
Post at 2009-1-31 15:32  Profile | Blog | P.M. 
所谓动态数组就是指针而已,你要保证返回的指针在你使用完毕前都有效,

直接返回函数内部变量是不行的,因为当函数执行完毕后,自动分配的内存地址将回收。

你可以用out参数,或直接用指针




做人要厚道,看帖要回贴
Top
softbug
新警察
Rank: 1



UID 1787
Digest Posts 0
Credits 20
Posts 8
点点分 20
Reading Access 10
Registered 2006-2-9
Status Offline
Post at 2009-2-12 21:41  Profile | Blog | P.M. 
NEw一个全局指针,返回这个指针即可
不用的时候 dispose掉即可!
Top
zjy
管理员
Rank: 9Rank: 9Rank: 9



UID 2
Digest Posts 6
Credits 2385
Posts 1543
点点分 2385
Reading Access 102
Registered 2002-12-16
Location China
Status Offline
Post at 2009-2-13 20:13  Profile | Site | Blog | P.M. 
回复 #1 inhagk 的帖子

在 Delphi 中新建一个 DLL 工程时,在 dpr 中有这样的注释:
{ 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. }

Delphi 要求在 DLL 和 EXE 之间导出 string、动态数组等自管理生存周期的对象时,将 ShareMem 放在 dpr 的 uses 列表第一项,以通过 BORLNDMM.DLL 为 DLL 和 EXE 提供共享的内存管理器。

如果不想用 ShareMem,就不要导出字符串和动态数组,而用 PChar、GetMem 等手工维护内存生命周期的指针来代替。

另外一个替代的方法是使用第三方的内存管理器 FastMM:
http://sourceforge.net/projects/fastmm/




Zhou JingYu
CnPack Administrator
http://www.cnpack.org/
Top
 




All times are GMT++8, the time now is 2024-11-24 06:15

    本论坛支付平台由支付宝提供
携手打造安全诚信的交易社区 Powered by Discuz! 5.0.0  © 2001-2006 Comsenz Inc.
Processed in 0.010044 second(s), 8 queries , Gzip enabled

Clear Cookies - Contact Us - CnPack Website - Archiver - WAP