CnPack Forum » 技术板块灌水区 » DLL返回动态数组


2009-1-9 08:13 inhagk
DLL返回动态数组

请教大家一个问题:我的DLL返回一个动态数组怎么老是报内存错误?

2009-1-31 15:32 bahamut8348
所谓动态数组就是指针而已,你要保证返回的指针在你使用完毕前都有效,

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

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

2009-2-12 21:41 softbug
NEw一个全局指针,返回这个指针即可
不用的时候 dispose掉即可!

2009-2-13 20:13 zjy
回复 #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:
[url=http://sourceforge.net/projects/fastmm/]http://sourceforge.net/projects/fastmm/[/url]

页: [1]
查看完整版本: DLL返回动态数组


Powered by Discuz! Archiver 5.0.0  © 2001-2006 Comsenz Inc.