欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C# 调用Delphi dll 实例代码

程序员文章站 2023-12-20 21:27:46
delphi dll 源码: 复制代码 代码如下:library dllres;   type     char10...

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);
        }
    }

上一篇:

下一篇: