奇怪,当我从DLL调用函数时,应用程序无法启动,但未发现错误 [英] Strange, when i call function from DLL, application not start but no error found

查看:78
本文介绍了奇怪,当我从DLL调用函数时,应用程序无法启动,但未发现错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的项目中,我有Windows应用程序和dll.我已经这样写了dll:

in mine project i have a Windows application and a dll. I have wrote dll so:

library MyDLL;

uses
  System.SysUtils,
  System.Classes;

{$R *.res}

function Prova: string; export;
begin
  result := 'prova';
end;

exports Prova;

begin
end.

在主程序中我调用了例程,所以:

and in main program i have called routine so:

unit FrmMain;

interface

uses
 // declaration uses // 

function Prova: string; external 'MyDLL.dll';

type    
 // declaration type //

implementation

begin
  ...
  TAdvEdit1.Text := Prova;  // [1] // 
  ...
end;

end.

当我编译所有项目时,未报告错误,状态报告为SUCCESS,但应用程序未启动.如果我删除行[1],则它可以正常工作.通常,当我调用函数Prova时,应用程序无法启动.我能解决什么问题?非常感谢.

When i compile all project not is reported error, and status report SUCCESS, but application not start. If i remove the line [1] then it works correctly. In general, application not start when i call the function Prova. What i can solve this problem? Thanks very much.

推荐答案

您的程序和DLL具有单独的内存管理器.通常,不应在应用程序内部使用从DLL分配的内存(反之亦然).分配来自哪里?在Delphi中,字符串"是托管类型,即,当您将某些文本分配给字符串变量时(在您的情况下,结果为:='prova'),Delphi(在幕后)使用DLL的内存管理器为该字符串分配内存.然后,例如,如果您在主应用程序中分配了其他文本值,则重新分配将使用应用程序的内存管理器,这很不好,即应用程序的MM正在触摸尚未分配自身的内存.

Your program and your DLL have separate memory manager. As a general rule memory allocated from DLL should not be used inside your application (the opposite is also true). Where the allocation comes from? In Delphi "string" is managed type i.e. when you assign some text to a string variable (in your case result := 'prova'), Delphi (behind the scene) allocates memory for that string using DLL's memory manager. Then, for example, if you assign other text value within your main application, the reallocation uses application's memory manager which is bad i.e. app's MM is touching memory that it hasn't allocated itself.

要解决此问题,您必须在应用程序(.dpr文件)和DLL中包括"SimpleShareMem"(Delphi> = 2010 IIRC?)单元作为您的USES子句的第一单元.:

To solve this issue you have to include "SimpleShareMem" (Delphi >= 2010 IIRC?) unit as the first unit of your USES clause in the application (.dpr file) AND in the DLL:

library MyDLL;

uses
  SimpleShareMem, // **MUST BE THE FIRST UNIT**
  System.SysUtils,
  System.Classes;
...


program YourApp;

uses
  SimpleShareMem, // **MUST BE THE FIRST UNIT**
  // declaration uses // 

可以在"开始>程序> Embarcadero RAD中找到这种方法的示例.Studio>示例> Delphi> RTL> SimpleShareMem "

您还可以使用PCHAR在DLL和APP之间传输字符串.

You can also use PCHAR to transfers strings between DLL and the APP.

这篇关于奇怪,当我从DLL调用函数时,应用程序无法启动,但未发现错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆