请教:Delphi调用VC++的DLL出错(200分)

  • 主题发起人 主题发起人 flai
  • 开始时间 开始时间
F

flai

Unregistered / Unconfirmed
GUEST, unregistred user!
环境:Win2k,Delphi5,VC++6.0

VC++ DLL 源码如下:
===========================
#include "stdafx.h"
BOOL APIENTRY DllMain( HANDLE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
return TRUE;
}

extern "C" _declspec(dllexport) int SendReceive(unsigned char far *SendBuf,unsigned char far *RcvBuf,int BufLen)
{
RcvBuf[0]='/0';
strcpy((char*)RcvBuf,"Test");
return 8888;
}
Delphi 调用源码如下:
===========================
unit Unit1;

interface

uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls;

type
TForm1 = class(TForm)
Button1: TButton;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
function SndRec(SndStr : string; var RecStr : string): integer;
end;
type
TCall=function(Snd:String; Rec:string):integer; stdcall;//cdecl;
var
Form1: TForm1;
implementation
{$R *.DFM}
function TForm1.SndRec(SndStr: string; var RecStr: string): integer;
Var
Handle:THandle;
MeCall:TCall;
begin
Handle:=LoadLibrary('Flair.DLL');
if Handle<>0 then begin
try
@MeCall:=GetProcAddress(Handle,'SendReceive');
if @MeCall=nil then exit;
SetLength(RecStr, 1024);
try
Result := MeCall(SndStr,RecStr);
except
ShowMessage('联接有错!');
Result := -300;
end;
finally
FreeLibrary(Handle);
end;
end;
end;
procedure TForm1.Button1Click(Sender: TObject);
Var
Result:Integer;
r:String;
Strs:TStrings;
begin
Strs:=TStringList.Create;
result:=SndRec(' ',r);
r:=trim(r);
ShowMessage(r);
ShowMessage(IntToStr(Result));
strs.Add(r); //***********出错的地方在这:前面几句执行都正常,并且r的值
//**********正是DLL返回的值
//**********但执行到这一句时出错: Access violation......
//**********并且,此句换成Caption:='Hello';或是Caption:=R;等等,系统报同样的错
//***********这是为什么???
Strs.SaveToFile('c:/r.txt');
Strs.Free;
end;
end.
====================================
谢谢各位指教!!!
 
试试修改参数类型:string ->PChar;
还有,两处函数的声明要一致,参数的多少也要一致,不然会造成内存结构上的错位的。
 
sorry,发贴子时有一个地方写错了:
extern "C" _declspec(dllexport) int SendReceive(unsigned char far *SendBuf,unsigned char far *RcvBuf,int BufLen)
实际源码应该是:
extern "C" _declspec(dllexport) int SendReceive(unsigned char far *SendBuf,unsigned char far *RcvBuf)
谢谢!
 
自己搞定了。
extern "C" _declspec(dllexport) int SendReceive(unsigned char far *SendBuf,unsigned char far *RcvBuf)

-->

extern "C" _declspec(dllexport) pascal int SendReceive(unsigned char far *SendBuf,unsigned char far *RcvBuf)

即可。

这里人气好像没以前旺了。
 
后退
顶部