日期:2014-05-17  浏览次数:21015 次

我用C#调用一个C++的DLL,出现错误,请帮忙解决,明天上班给分
首先看一下DLL的说明文档:RdrReader433A.dll
1、打开串口:int RdrOpenPort(char *port)
2、关闭串口:int RdrClosePort(char *port)
3、获得卡号报文:int RdrGetCardId(char *port, char *outcardid)

我只是做一个DEMO来看看效果。可是报错。
我在添加引用DLL的时候报错:未能添加对“.DLL”的引用。请确保此文件可访问并且是一个有效的程序集或COM组件。
于是我换另一种方法来引用此DLL。
首先我做了一个桌面程序,别的没有,只有一个按钮和一个文本框。下边是我的代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
namespace WindowsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        [DllImport("RdrReader433A.dll", EntryPoint = "RdrOpenPort")]
        public static extern int RdrOpenSerialPort433(string port);
        [DllImport("RdrReader433A.dll", EntryPoint = "RdrGetCardId", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall)]

        //public static extern int RdrGetCardidBy433(string port, char* recvdata);
        public static extern int RdrGetCardidBy433(string port,out StringBuilder recvdata);
        [DllImport("RdrReader433A.dll", EntryPoint = "RdrClosePort")]
        public static extern int RdrCloseSerialPort433(string port);
        //[MarshalAs(UnmanagedType.LPArray)]
        //public byte[] str = new byte[1024];


        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                this.textBox1.Text = RdrOpenSerialPort433("COM1").ToString();
                textBox1.Text += "|";
                StringBuilder str;

                this.textBox1.Text += RdrGetCardidBy433("COM1", out str).ToString();
                textBox1.Text += "|";
                this.textBox1.Text += str.ToString();
                textBox1.Text += "|";