新文章 网摘 文章 随笔 日记

C# 调用Delphi的dll

一、Delphi7=>File=>New=>Other=>DLL Wizard,然后输入以下代码:

library dllres;

uses
  SysUtils, Classes,Dialogs;

{$R *.res}

function Plus(x, y: integer): Integer; stdcall;
begin
  Result:= x + y;
end;


procedure  Hello( a, b:WideString; out return : WideString) ;stdcall
begin
   return:= a+ b;
end;


exports
  Plus,Hello;
begin
end.

按Ctrl+F9生成dll

二、C# 中新建Winform程序,设置目标框架为x86

1、把Delphi生成的dll复制到C#的exe文件夹下

2、在C# 中添加如下代码:

    /// <summary>
    /// C# 调用Delphi Dll的样例
    /// </summary>
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            //调用求和的方法
            int a = Plus(1, 2);

            string ip = "ABCDEF老天____";
            string workOrder = "REA22C100A";

            //调用返回字符串的方法
            string result;
            Hello(ip, workOrder, out result);

            //为了设置个断点,多写下面这句代码
            int x = 2;
        }

        /// <summary>
        /// 引入Delphi的求和方法
        /// </summary>
        /// <param name="x"></param>
        /// <param name="y"></param>
        /// <returns></returns>
        [DllImport(@"dllres.dll", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall)]
        public static extern int Plus(int x, int y);

        /// <summary>
        /// 引入Delphi的返回字符串的方法
        /// </summary>
        /// <param name="a"></param>
        /// <param name="b"></param>
        /// <param name="result"></param>
        [DllImport(@"dllres.dll", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall)]
        public static extern void Hello(
            [MarshalAs(UnmanagedType.BStr)]string a,
            [MarshalAs(UnmanagedType.BStr)]string b,
            [MarshalAs(UnmanagedType.BStr)]out string result);

    }

 

参考文献:

[已解决]-在 C#-C 中使用 Delphi DLL# (appsloveworld.com)

posted @ 2022-12-19 18:55  岭南春  阅读(741)  评论(0编辑  收藏  举报