Delphi編寫DLL供C#調用的實例


Delphi中編寫的Dll:

library TestDLL;

{ Important note about DLL memory management: ShareMem must be the
  first unit in your library's USES clause AND your project's (select
  Project-View Source) USES clause if your DLL exports any procedures or
  functions that pass strings as parameters or function results. This
  applies to all strings passed to and from your DLL--even those that
  are nested in records and classes. ShareMem is the interface unit to
  the BORLNDMM.DLL shared memory manager, which must be deployed along
  with your DLL. To avoid using BORLNDMM.DLL, pass string information
  using PChar or ShortString parameters. }

uses
  SysUtils,
  Classes;
function ADD(X,Y:Integer):Integer;stdcall;
begin
  Result :=X+Y;
end;
function Txx(x,y:Double):Double ;stdcall ;
begin
  Result :=x+y+y+x;
end;
function EncryVncPassStrHex(Str: PChar): PChar;stdcall;

var
  TempResult: String;
begin
  TempResult := WideCharToString(str);
  Result := PChar(TempResult);
end;
{$R *.res}
exports
   ADD,
   EncryVncPassStrHex,
   Txx;
begin
end.

其中涉及到三個輸出函數:一個輸出的變量為整數,一個為浮點數,另一個為字符串。

C#中調用該Dll:

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using System.Runtime.InteropServices;

namespace UseDLL
{
    /// <summary>
    /// Description of MainForm.
    /// </summary>
    public class UseDLL
    {
        [DllImport("TestDLL.DLL",EntryPoint="ADD",CharSet= CharSet.Auto,CallingConvention=CallingConvention.StdCall)]
        public static extern int add(int x,int y);
        [DllImport("TestDLL.DLL",EntryPoint="Txx",CharSet= CharSet.Auto,CallingConvention=CallingConvention.StdCall)]
        public static extern double PP(double x,double y);
        [DllImport("TestDLL.DLL", EntryPoint="EncryVncPassStrHex",CharSet=CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
         public static extern string EncryVncPassStrHex( string Str);
    }

    public partial class MainForm : Form
    {
        public MainForm()
        {
            //
            // The InitializeComponent() call is required for Windows Forms designer support.
            //
            InitializeComponent();
            
            //
            // TODO: Add constructor code after the InitializeComponent() call.
            //
        }
        
        void Button1Click(object sender, EventArgs e)
        {
            int x=10;
            int y=100;
            int z=UseDLL.add(x,y);
            this.textBox1.Text=z.ToString();
            double oo=0.123;
            double pp=0.254;            
            this.button1.Text=UseDLL.PP(oo,pp).ToString();
            this.Text =UseDLL.EncryVncPassStrHex("我是XXX");
        }
    }
}

注意:在C#的using部分必須添加“using System.Runtime.InteropServices”。

程序運行結果為:

 本程序在delphi2010和SharpDevelop通過。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM