C# 调用Delphi dll 实例代码

delphi dll 源码: 复制代码 代码如下:library dllres; type char10 = array[0 9] of char

delphi dll 源码:

复制代码 代码如下:

library dllres;

  type
     char10 = array[0..9] of char;
     TMydata = packed record
       id: Integer;
       name: char10;
       married: Boolean;
       salary: Double;
     end;
    PMydata = ^TMydata;

  const
    RESSTR: array[0..4] of string = ('HELLO', 'COLOR', 'DELPHI', 'shared', 'library');
    NO_RESULT=   'no result';
  var
   mydata: TMydata;

{$R *.res}
  // 返回字符串指针
  function  getResStr(aindex: Integer): PChar;  stdcall;
  begin
    if aindex < Length(RESSTR) then
    begin
      Result := pchar(RESSTR[aindex]);
    end
    else
    begin
      Result := pchar(NO_RESULT);
    end;
  end;

  // 返回结构体指针
  function getMydata: PMydata; stdcall;
  begin
    with mydata do
    begin
      id := 123;
      name := 'obama';
      married := false;
      salary := 1200;
    end;
    Result := @mydata;
  end;

exports   getResStr, getMydata;

begin
end.


C# 调用示例:

复制代码 代码如下:

class Invoke_Delphi_Dll_Exam
    {
        [DllImport("dllres.dll", CallingConvention = CallingConvention.StdCall)]
        public static extern IntPtr getResStr(int index);

        [DllImport("dllres.dll", CallingConvention = CallingConvention.StdCall)]
        public static extern IntPtr getMydata();

        public struct Mydata
        {
            public int id; //0
            public string name; //4
            public bool married; //24
            public double salary; //25

            public Mydata(byte[] data)
            {
                if (data != null && data.Length == 33) {
                    id = BitConverter.ToInt32(data, 0);
                    name = Encoding.Unicode.GetString(data, 4, 20).Replace("\0",""); // 去掉尾部的0字符
                    married = BitConverter.ToBoolean(data, 24);
                    salary = BitConverter.ToDouble(data, 25);
                }
                else {
                    id = 0;
                    name = String.Empty;
                    married = false;
                    salary = 0;
                }
            }

            public override string ToString()
            {
                return String.Format("id: {0}, name: {1}, married: {2}, salary: {3}",
                    id, name, married, salary);
            }
        }

        private static void Main(string[] args)
        {
            Console.WriteLine(Marshal.PtrToStringAuto(getResStr(0)));

            byte[] data = new byte[33];
            Marshal.Copy(getMydata(), data, 0, 33);
            Mydata mydata = new Mydata(data);
            Console.WriteLine(mydata);
        }
    }

您可能有感兴趣的文章
Delphi 生成excel中饼图的实例代码

delphi中如何读取Excel数据?delphi中读取Excel数据详解

delphi如何使用Chilkat 组件和库从SFTP下载文件的方法

DELPHI7.0 获取硬盘、CPU、网卡序列号的代码

运行程序提示access violation at address的如何解决方法