Использование AwId.dll в delphi XE6 - PullRequest
0 голосов
/ 23 января 2019

Я никогда раньше не звонил в C # dll, и когда я искал в интернете, я все больше сбивался с толку.

Как я понимаю, мне нужно создать процедуру / функции dll.

У меня есть пример кода C # и там он объявлен следующим образом.

private delegate void OpCompletedDelegate(AwidMpr.OperationCompleteEventArgs e);
private delegate void TagReadResponseDelegate(AwidMpr.TagReadEventArgs e);
private delegate void DeviceErrorDelegate(AwidMpr.ErrorEventArgs e);

Я попробовал это в интерфейсе:

procedure OperationCompleteEventArgs (); stdcall;

Но я думаю, что мне не хватает некоторых параметров дляe, который показывает в C #

Я пытался добавить это в реализации, но это не работает, я получаю сообщение об ошибке, говорящее, что функция нуждается в типе результата ..

const 
  AwidMpr= 'AwidMpr.dll';
  procedure OperationCompleteEventArgs; external AwidMpr name 'OperationCompleteEventArgs';  

Я понимаючто в любой функции должен быть результат, но в объявлении C # я просто вижу ae

Вот демонстрационная программа на C #, поставляемая с dll.

Надеюсь, что кто-то может меня достатьв правильном направлении, спасибо.

namespace AWIDMPRSimpleReadDemo
begin
    public partial class Form1 : Form
    begin
        private delegate void OpCompletedDelegate(AwidMpr.OperationCompleteEventArgs e);
        private delegate void TagReadResponseDelegate(AwidMpr.TagReadEventArgs e);
        private delegate void DeviceErrorDelegate(AwidMpr.ErrorEventArgs e);

        #region Variables
        private const string DATA_TABLE_NAME := 'TagInventory';
        private Integer _activeTagInventorySize;
        private DataTable _tagInventoryTable := null;
        private Integer _defaultTagInventorySize := 50;
        private const string COL_TAG_ID := 'EPC Number/Tag ID/Data';
        private const string COL_CNT := 'Reads';
        private const string COL_FIRST := 'First';
        private const string COL_LAST := 'Last';

        private byte cmd := 0x00;
        private string cmdStr := 'Single Tag ID';
        private AwidMpr.MprDevice device := null;
        private ArrayList tagsRead := null;
        private string origTitle := null;

        private Boolean isNetwork := true;
        #endregion

        private void InitializeTagInventoryTable()
        begin
            Integer sz := Properties.Settings.Default.TagInventorySize;
            if (sz < := 0) then
                _activeTagInventorySize := _defaultTagInventorySize
            else _activeTagInventorySize := sz;
            this._tagInventoryTable := new DataTable(DATA_TABLE_NAME);

            DataColumn col := new DataColumn(COL_TAG_ID, Type.GetType('System.String'));
            this._tagInventoryTable.Columns.Add(col);

            col := new DataColumn(COL_CNT, Type.GetType('System.String'));
            this._tagInventoryTable.Columns.Add(col);

            col := new DataColumn(COL_FIRST, Type.GetType('System.String'));
            this._tagInventoryTable.Columns.Add(col);

            col := new DataColumn(COL_LAST, Type.GetType('System.String'));
            this._tagInventoryTable.Columns.Add(col);
        end;
        private DataRow RowInTable(DataTable dt, DataRow drCheck, string criteriaColumn)
        begin
            DataRow drMatch := null;
            foreach (DataRow drExisting in dt.Rows)
            begin
                if (drExisting[criteriaColumn].ToString() = drCheck[criteriaColumn].ToString()) then
                begin
                    drMatch := drExisting;
                    break;
                end;
            end;

            (* C2PAS: Exit *) Result := drMatch;
        end;
        public Form1()
        begin
            InitializeComponent();
#if UseLogo
else
            this.pictureBox1.Visible := false;
#endif
            var app := Assembly.GetExecutingAssembly() then .GetName();
            this.Text := ' ' + app.Name + ' V' + app.Version;
#if DEBUG
else
            this.Text + := ' (AwidMpr: ' + AssemblyName.GetAssemblyName('AwidMpr.dll') then .Version + ')';
#endif
            this.origTitle := this.Text;
            this.InitializeTagInventoryTable();
            this.dataGridView1.DataSource := this._tagInventoryTable;
            this.dataGridView1.Columns[0].Width := 320;
            this.dataGridView1.Columns[1].Width := 130;
            this.dataGridView1.Columns[2].Width := 200;
            this.dataGridView1.Columns[3].Width := 200;
        end;

        private void toolStripMenuItem_Click(object sender, EventArgs e)
        begin
            string name := ((ToolStripMenuItem)sender).Name;
            ToolStripMenuItem[] mbrs := begin this.toolStripMenuItem2, this.toolStripMenuItem3,
                this.toolStripMenuItem4 end; ;
            foreach (ToolStripMenuItem mtm in mbrs)
            begin
                if (name.Equals(mtm.Name)) then continue;
                mtm.Checked := false;
            end;
            this.cmdStr := ((ToolStripMenuItem)sender).Text;
            string val := this.cmdStr.ToLower();
            if (val.Contains('single tag id')) then this.cmd := 0x00
            else if (val.Contains('meter')) then this.cmd := 0x11
            else if (val.Contains('portal')) then this.cmd := 0x1E;
        end;
        private void btnStartStop_Click(object sender, EventArgs e)
        begin
            Button btn := (Button)sender;
            if ( not this.device.Connected) then
            begin
                MessageBox.Show('Device not connected! Get out.', btnClear.Text,
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
                (* C2PAS: Exit *) Result :=;
            end;
            if (btn.Text.Equals('Start')) then
            begin
                if (this.tagsRead <> null) then this.tagsRead.Clear();
                this._tagInventoryTable.Clear();
                try
                begin
                    case (this.cmd) of
                    begin
                        0x00:
                            this.device.StartEpcC1G2ReadSingleTagId();
                            break;
                        0x11:
                            this.device.StartEpcC1G2SingleTagMeter();
                            break;
                        0x1E:
                            this.device.StartEpcC1G2PortalIds(0, 0);
                            break;
                        else
                            (* C2PAS: Exit *) Result :=;
                    end;
                end;
                except (Exception ex)
                begin
                    MessageBox.Show(ex.Message, 'Executing ''' + this.cmdStr + '''',
                        MessageBoxButtons.OK, MessageBoxIcon.Error);
                    (* C2PAS: Exit *) Result :=;
                end;
                btn.Text := 'Stop';
                this.btnClear.Enabled := this.panel1.Enabled := this.menuStrip1.Enabled := false;
            end
            else
            begin
                try
                begin
                    this.doStop();
                end;
                except (Exception ex)
                begin
                    MessageBox.Show(ex.Message, 'Stop', MessageBoxButtons.OK, MessageBoxIcon.Error);
                    (* C2PAS: Exit *) Result :=;
                end;
                btn.Text := 'Start';
                this.btnClear.Enabled := this.panel1.Enabled := this.menuStrip1.Enabled := true;
            end;
        end;
        private void btnClear_Click(object sender, EventArgs e)
        begin
            this._tagInventoryTable.Clear();
        end;
        private void doConnect()
        begin
            if (this.device <> null and this.device.Connected) then
            begin
                try
                begin
                    this.device.Disconnect();
                end;
                except (Exception e)
                begin
                    MessageBox.Show(e.Message, 'Close old connection', MessageBoxButtons.OK, MessageBoxIcon.Error);
                    (* C2PAS: Exit *) Result :=;
                end;
                this.device := null;
            end;
            string s := null;
            try
            begin
                if (this.isNetwork) then
                begin
                    this.device := new AwidMpr.MprDevice(new AwidMpr.TcpConnectionSettings(
                        this.tbxIP.Text.Trim(), 4000));
                    s := this.device.Connect(true);
                end
                else
                begin
                    this.device := new AwidMpr.MprDevice(new AwidMpr.SerialConnectionSettings(
                        this.cbxComPort.Text, Convert.ToInt32(this.cbxSpeed.Text)));
                    this.device.Connect();
                end;
            end;
            except (Exception e)
            begin
                s := 'Make sure ' + (this.isNetwork ? 'IP' : 'COM Port/Speed combo') + ' entry is valid.';
                MessageBox.Show(e.Message + Environment.NewLine + s, 'Connect',
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
                this.tbxIP.Focus();
                (* C2PAS: Exit *) Result :=;
            end;
            try
            begin
                System.Threading.Thread.Sleep(20);
                s := this.device.GetFirmwareVersion();
            end;
            except (Exception e)
            begin
                MessageBox.Show('Initial FWV Retrieval failed: ' + e.Message, 'Connect',
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            end;
            this.Text + := ' ' + s;
            s := null;
            this.device.TagRead + := new EventHandler<AwidMpr.TagReadEventArgs>(device_TagRead);
            this.device.Error + := new EventHandler<AwidMpr.ErrorEventArgs>(device_Error);
            this.device.OperationCompleted + :=
                new EventHandler<AwidMpr.OperationCompleteEventArgs>(device_OperationCompleted);
            this.panel2.Enabled := this.menuStrip1.Enabled := true;
            this.button1.Text := 'Disconnect';
            this.panel3.Enabled := false;
        end;
        public void logUpdate(string s)
        begin
            if (this.txtLog.Text.Length + s.Length > this.txtLog.MaxLength) then
            begin
                this.txtLog.Text := '';
            end;
            this.txtLog.Text + := (this.txtLog.Text.Length > 0 ? Environment.NewLine : '') +
                DateTime.Now.ToString() + ' ' + s;
        end;
        private void device_OperationCompleted(object sender, AwidMpr.OperationCompleteEventArgs e)
        begin
            //throw new NotImplementedException();
            this.logUpdate('Cmd: ' + e.Command.ToString() + ', Protocol: ' + e.CommandType.ToString() +
                ', Status: ' + e.Status.ToString());
        end;
        private void device_Error(object sender, AwidMpr.ErrorEventArgs e)
        begin
            //throw new NotImplementedException();
            this.logUpdate('Device Error: ' + e.Exception.ToString());
        end;
        private void device_TagRead(object sender, AwidMpr.TagReadEventArgs e)
        begin
            //throw new NotImplementedException();
            try
            begin
                Control ctrl := this.dataGridView1;
                if (ctrl.InvokeRequired) then
                begin
                    //IAsyncResult result = // needed if will use EndInvoke which is not req'd on controls
                    ctrl.BeginInvoke(new TagReadResponseDelegate(this.displayTag),
                    new object[] begin e end; );
                end
                else this.displayTag(e);
            end;
            except (Exception ex)
            begin
                // what do we do here????
                string errMsg := '';
                errMsg + := ex.Message;
            end;
        end;
        private void doDisconnect()
        begin
            if (this.device <> null) then
            begin
                try
                begin
                    if (this.device.Connected) then this.device.Disconnect();
                end;
                except (Exception e)
                begin
                    MessageBox.Show(e.Message, 'Disonnect', MessageBoxButtons.OK, MessageBoxIcon.Error);
                end;
                this.device := null;
            end;
            this._tagInventoryTable.Clear();
            this.txtLog.Text := '';
            this.panel2.Enabled := this.menuStrip1.Enabled := false;
            this.button1.Text := 'Connect';
            this.Text := this.origTitle;
            this.panel3.Enabled := true;
        end;
        private void ConnectClick(object sender, EventArgs e)
        begin
            if (((Button)sender).Text.Equals('Connect')) then
                this.doConnect()
            else this.doDisconnect();
        end;
        private string getTimeStamp()
        begin
            DateTime dt := DateTime.Now;
            string timeVal := String.Format('{0:D2}:{1:D2}:{2:D2}:{3:D3}' +
                ' {4:D2}/{5:d2}/{6:d4}',
                dt.Hour, dt.Minute, dt.Second, dt.Millisecond,
                dt.Month, dt.Day, dt.Year);
            (* C2PAS: Exit *) Result := timeVal;
        end;
        private void displayTag(AwidMpr.TagReadEventArgs args)
        begin
            if (args.TagId = null or args.TagId.Length < := 1) then (* C2PAS: Exit *) Result :=;
            if (this.tagsRead = null) then this.tagsRead := new ArrayList(1);
            string timestamp := '';
            try
            begin
                if (this._tagInventoryTable <> null and this._tagInventoryTable.Columns.Count > 0) then
                begin
                    AwidMpr.TagReadEventArgs e := args;
                    DataRow dr := this._tagInventoryTable.NewRow();
                    string tagID := (e.TagId = null or e.TagId.Length < := 0 ?
                        'null' : AwidMpr.Utility.ByteArrayToHexString(e.TagId));
                    if ( not this.tagsRead.Contains(tagID)) then
                    begin
                        this.tagsRead.Add(tagID);
                    end;

                    dr[COL_TAG_ID] := tagID;
                    timestamp := this.getTimeStamp();
                    dr[COL_LAST] := timestamp;
                    Integer readCount := e.TagReadCount;

                    lock (this._tagInventoryTable)
                    begin
                        if (this._tagInventoryTable.Rows.Count = this._activeTagInventorySize) then
                        begin
                            this._tagInventoryTable.Rows.RemoveAt(this._tagInventoryTable.Rows.Count - 1);
                        end;

                        DataRow existingTag := //(e.Command == 0x11 ? null :
                            this.RowInTable(this._tagInventoryTable, dr, COL_TAG_ID)
                            //)
                        ;

                        if (existingTag = null) then
                        begin
                            dr[COL_FIRST] := timestamp;
                            dr[COL_CNT] := readCount;
                            this._tagInventoryTable.Rows.InsertAt(dr, 0);
                        end
                        else
                        begin
                            readCount + := Convert.ToInt16(existingTag[COL_CNT]);
                            existingTag[COL_CNT] := readCount;
                            existingTag[COL_LAST] := timestamp;
                        end;
                    end;
                end;
            end;
            except (Exception e)
            begin
                throw e;
            end;
        end;
        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        begin
            this.doDisconnect();
        end;
        private void doStop()
        begin
            try
            begin
                this.device.Stop();
            end;
            except (Exception e)
            begin
                throw e;
            end;
        end;
        private void StopClicked(object sender, EventArgs e)
        begin
            try
            begin
                this.doStop();
            end;
            except (Exception ex)
            begin
                MessageBox.Show(ex.Message, 'Stop', MessageBoxButtons.OK, MessageBoxIcon.Error);
            end;
        end;
        private void CommunicationModeChanged(object sender, EventArgs e)
        begin
            RadioButton rb := (RadioButton)sender;
            if (rb.Checked) then
            begin
                if (rb.Text.Contains('Serial')) then
                begin
                    this.isNetwork := false;
                end
                else
                begin
                    this.isNetwork := true;
                end;
                this.gbxSerial.Visible := not this.isNetwork;
                this.gbxIP.Visible := this.isNetwork;
            end;
        end;
        private void ComPortDropDown(object sender, EventArgs e)
        begin
            ComboBox cbCom := (ComboBox)sender;
            string[] strCom := System.IO.Ports.SerialPort.GetPortNames();
            cbCom.Items.Clear();
            foreach (string s in strCom)
            begin
                cbCom.Items.Add(s);
            end;
        end;
    end;
end;
...