我正在尝试从Delphi调用C++代码。我是初学者。虽然它是间歇性的(但非常普遍),但我不断收到访问冲突错误。
这只发生在执行ConfigccDLL
或者PriorTran
时。根据我所读的,可能是调用约定不匹配,但是我印象中两个代码库都使用了stdcall
。我已经使用Dependency Walker检查了我创建的dll,并且显示函数名为_functionName。我不确定是否应该带有前导下划线来调用它们。我希望尽可能少地更改Delphi代码,因为最终将使用dll的代码我不能改变(我原本想说我完全不能改变它,但为了使Delphi编译通过,我已经不得不改变PAnsiChar并添加AnsiStrings)。
Delphi代码:
unit dllTest;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, Buttons, AnsiStrings;
procedure CloseDLL; stdcall; external 'cccontrol.dll';
procedure ConfigccDLL(Variables: PAnsiChar); stdcall; external 'cccontrol.dll';
procedure PrepareDLL; stdcall; external 'cccontrol.dll';
procedure PriorTran(Variables: PAnsiChar); stdcall; external 'cccontrol.dll';
type
TdllTestForm = class(TForm)
PrepareBtn: TBitBtn;
Label1: TLabel;
ConfigccDLLbtn: TBitBtn;
TranTypeEntry: TEdit;
TranAmountEntry: TEdit;
Label2: TLabel;
PriorTranBtn: TBitBtn;
TranIDEntry: TEdit;
Label3: TLabel;
CloseDLLBtn: TBitBtn;
Label4: TLabel;
Memo1: TMemo;
BitBtn1: TBitBtn;
procedure CloseDLLBtnClick(Sender: TObject);
procedure PriorTranBtnClick(Sender: TObject);
procedure ConfigccDLLbtnClick(Sender: TObject);
procedure PrepareBtnClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
dllTestForm: TdllTestForm;
implementation
{$R *.dfm}
procedure TdllTestForm.PrepareBtnClick(Sender: TObject);
var
AppHandle: HWND;
begin
AppHandle := Application.Handle;
PrepareDLL;
end;
procedure TdllTestForm.ConfigccDLLbtnClick(Sender: TObject);
var
Variables: AnsiString;
TransID, TransType, TranAmt: string;
begin
TransType := TranTypeEntry.Text;
TranAmt := TranAmountEntry.Text;
Variables := TransType + '^' + TranAmt + '^';
ConfigccDLL(PAnsiChar(Variables));
end;
procedure TdllTestForm.PriorTranBtnClick(Sender: TObject);
var
Variables: AnsiString;
TransID, TransType, TranAmt: string;
begin
TransID := TranIDEntry.Text;
Variables := TransID;
PriorTran(PAnsiChar(Variables));
end;
procedure TdllTestForm.CloseDLLBtnClick(Sender: TObject);
begin
CloseDLL;
end;
end.
以下是C++代码:
头文件:
#pragma once
#ifndef ccControl
#define ccControl
#include <iostream>
#if defined DLL_EXPORT
#define DECLDIR __declspec(dllexport)
#else
#define DECLDIR __declspec(dllimport)
#endif
extern "C" {
DECLDIR void __stdcall PrepareDLL();
DECLDIR void __stdcall ConfigccDLL(char* pcharVar);
DECLDIR void __stdcall PriorTran(char* pcharVar);
DECLDIR void __stdcall CloseDLL();
}
#endif
Cpp文件:
#include "stdafx.h"
#include <iostream>
#include <windows.h>
#include <Winuser.h>
#include <stdexcept>
#define DLL_EXPORT
#include "ccControl.h"
#pragma warning( disable : 4996 )
using namespace std;
extern "C" {
DECLDIR void __stdcall PrepareDLL()
{
}
DECLDIR void __stdcall ConfigccDLL(char* pcharVar)
{
}
DECLDIR void __stdcall PriorTran(char* pcharVar)
{
}
DECLDIR void __stdcall CloseDLL()
{
}
}
从依赖项查看器中看到的Dll
打开dll时,Dependency Walker也会出现这些错误。
_PriorTran@4
,而不是您的Delphi代码中所声明的PriorTran
。如果您想要在DLL中使用“干净”的导出名称,则需要使用模块定义文件构建您的DLL。 - PaulMcKenzie