当前位置: 移动技术网 > IT编程>开发语言>c# > C# 调用Delphi dll 实例代码

C# 调用Delphi dll 实例代码

2019年07月18日  | 移动技术网IT编程  | 我要评论
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);
        }
    }

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网