perl – 使用Win32 :: API调用OpenComPort

我在调用第三方dll控制rfid阅读器时遇到问题.

这是我的代码:

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

以下是该函数的原型:

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

该功能的文档由下图提供(对不起):

《perl – 使用Win32 :: API调用OpenComPort》

有人可以告诉我我做错了什么吗?当我调用该函数时,Perl解释器崩溃了!!

我在Win10上运行草莓Perl 5.24

最佳答案

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

   ...
}

未经测试.

点赞