在Delphi 10中制作的DLL在Visual Studio 2010中抛出异常

时间:2018-01-10 10:02:21

标签: c# visual-studio-2010 dll delphi-10.1-berlin

我在Delphi 10中以32位和64位制作了以下DLL。

library Project2;

uses SysUtils,Classes,Vcl.Dialogs;

  function showSqRoot(var a:Double):Double; stdcall; export;
  begin
      Result:=sqrt(a);
   end;

   exports showSqRoot;
  {$R *.res}

   begin
    end.

这是我用于导入DLL的Visual Studio代码,因为它在添加作为参考时出错。

using System;
using System.Windows.Forms;

namespace TestingImportDLL
{
    public partial class Form1 : Form
    {
        [System.Runtime.InteropServices.DllImport("Project2.dll", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl)]
        public static extern double showSqRoot(double a);

        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            double numInput, numRes;
            numInput = Convert.ToDouble(textBox1.Text);
            numRes = showSqRoot(numInput);
            textBox2.Text = numRes.ToString();
        }
    }
}

它会在此行引发以下异常:

    numRes = showSqRoot(numInput); //AccessViolationException was unhandled

Attempted to read or write protected memory. This is often an indication that other memory is corrupt.

以下是我的Delphi 10项目,它与DLL完美配合:

unit Unit1;

interface
uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls;

type
  TForm1 = class(TForm)
    Edit1: TEdit;
    Edit2: TEdit;
    Button1: TButton;
    Label1: TLabel;
    Label2: TLabel;
    procedure Button1Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;
function showSqRoot(var a:Double):Double;stdcall; external 'Project2.dll';
implementation

{$R *.dfm}
procedure TForm1.Button1Click(Sender: TObject);
var
        numInput,numRes:Double;   {Input and Result}
   begin
       numInput:=StrToFloat(Edit1.Text);
      numRes:=showSqRoot(numInput);   {call the function in DLL with the Parameter}
      Edit2.Text:=FloatToStr(numRes); {Display the Result}
    end;

end.

我已将DLL放在Visual Studio的bin / debug中。

任何帮助都将受到高度赞赏。

0 个答案:

没有答案