4

I am having trouble calling a third party dll to control an rfid reader. this is my code:

use Win32::API;
Win32::API::More->Import("kernel32", "int GetCurrentProcessId()");
Win32::API::More->Import("UHFReader288.dll", "OpenComPort","IPPI","I","_cdecl");

sub OpenReader {
    my $comport = 1;
    my $comAddr = " " x 255;
    my $baud = "5";
    my $handle = -1;

    my $result =  OpenComPort($comport,$comAddr,$baud ,$handle);

    return $result;
}

The following is the function's prototype:

int OpenComPort(int port, BYTE* ComAdr, BYTE baud, int* FrmHandle);

The function's documentation is provided by the following image (sorry):

Documentation for OpenComPort

Can someone please show me what I am doing wrong? When I call the function, the Perl interpreter crashes!!

I am running strawberry Perl 5.24 on Win10

ikegami
  • 367,544
  • 15
  • 269
  • 518
Njugu
  • 81
  • 3
  • @ikegami C prototype is "_cdecl" port-handle returns handle for the port to be used in related functions and unfortunately the manufacturer does not have a public library i can link (its Chinese), only a pdf document that i am unable to attach here. the c# code works with the same dll. – Njugu Oct 17 '17 at 12:26

1 Answers1

1
use strict;
use warnings qw( all );
use feature qw( state );

use Win32::API qw( );

use constant {
   COM1 => 1,
   COM2 => 2,
   COM3 => 3,
   COM4 => 4,
   COM5 => 5,
   COM6 => 6,
   COM7 => 7,
   COM8 => 8,
   COM9 => 9,
   # etc

   COM_ADR_BROADCAST => 0xFF,

   BAUD_9600   => 0,
   BAUD_19200  => 1,
   BAUD_38400  => 2,
   BAUD_57600  => 5,
   BAUD_115200 => 6,
};

sub OpenComPort {
   my ($port, $ComAdr_ref, $baud, $FrmHandle_ref) = @_;

   state $OpenComPort = Win32::API::More->new('UHFReader288.dll', 'OpenComPort', 'iPCP', 'i', '_cdecl')
      or die($^E);

   my $ComAdr_buf    = pack('C', $$ComAdr_ref);
   my $FrmHandle_buf = pack('i', -1);

   my $rv = $OpenComPort->Call($port, $ComAdr_buf, chr($baud), $FrmHandle_buf);

   $$ComAdr_ref    = unpack('C', $ComAdr_buf);
   $$FrmHandle_ref = unpack('i', $FrmHandle_buf);

   return $rv;
}

{
   my $ComAdr = COM_ADR_BROADCAST;
   my $FrmHandle;
   OpenComPort(COM1, \$ComAdr, BAUD_57600, \$FrmHandle)
      or die("Error");

   ...
}

Untested.

ikegami
  • 367,544
  • 15
  • 269
  • 518