我还在尝试在C#中使用C ++非托管dll。
我的问题是:
我有一个功能(来自我的dll): C ++:
INT APIENTRY ReadPIC(HANDLE hComPort, PIC *pic, BYTE PacketData[])
{
BYTE InData[MAX_PACKET]; //Allocate for one packet
INT RetStatus;
INT DatCount;
INT DatCount2 = 0;
switch (pic->BootCmd){
case COMMAND_READPM:
case COMMAND_READEE:
case COMMAND_READCFG:
break;
default: return ERROR_INVALID_COMMAND;
}
//Limit to 1 or 2 bytes per addr
if(!pic->BytesPerAddr) return ERROR_BPA_TOO_SMALL;
if(pic->BytesPerAddr > 2) return ERROR_BPA_TOO_BIG;
if(pic->BytesPerBlock < pic->BytesPerAddr) return ERROR_BLOCK_TOO_SMALL;
if(pic->BootDatLen > MAX_PACKET - 6) return ERROR_PACKET_TOO_BIG;
//Build header
InData[0] = pic->BootCmd;
InData[1] = pic->BootDatLen / pic->BytesPerAddr;
InData[2] = (BYTE)(pic->BootAddr & 0xFF);
InData[3] = (BYTE)((pic->BootAddr & 0xFF00) / 0x100);
InData[4] = (BYTE)((pic->BootAddr & 0xFF0000) / 0x10000);
RetStatus = SendGetPacket(hComPort, InData, 5, MAX_PACKET, pic->MaxRetrys);
if(RetStatus < 0) return RetStatus;
for (DatCount = 5; DatCount < RetStatus - 1; DatCount++){
PacketData[DatCount2] = InData[DatCount];
DatCount2++;
}
return DatCount2;
}
C#实施:
[DllImport(@"PICBOOT.dll")]
public static extern short ReadPIC(int hComPort, ref PIC pic, ref byte PacketData);
DevID[0] = (byte)CMD_READ_VERSION;
DevID[1] = (byte)0;
short RetStat;
PIC pic = new PIC();
pic.BootAddr = 0x3FFFFE;
pic.BootCmd = (byte)CMD_READ_PROG_MEM;
pic.BootDatLen = (byte)2;
pic.MaxRetrys = 3;
pic.BytesPerBlock = 1;
pic.BytesPerAddr = 1;
RetStat = com.Dll_PIC_interface.ReadPIC(PicBoots.PortHandle, ref pic, ref DevID[0]);
我也有一个相同功能的VB示例:
ReDim DevID(10) As Byte
Dim RetStat
Dim picb As PIC
DevID(0) = CMD_READ_VERSION
DevID(1) = 0
picb.BootAddr = &H3FFFFE
picb.BootCmd = CMD_READ_PROG_MEM
picb.BootDatLen = 2
picb.MaxRetrys = PicBootS.MaxRetry
picb.BytesPerBlock = 1
picb.BytesPerAddr = 1
RetStat = ReadPIC(PicBootS.PortHandle, picb, DevID(0))
If RetStat <= 0 Then
ReadDeviceID = "0"
Else
ReadDeviceID = CStr(((DevID(1) * 256) + DevID(0)) \ 32)
End If
C#one抛出错误(-11)谁必须配合:#define ERROR_BPA_TOO_BIG -11
这是我第一次使用非托管dll,不知道为什么它不知道,我认为我非常接近VB的例子。
C ++结构实现
//PIC structure used for some functions
typedef struct _PIC {
BYTE BootCmd;
BYTE BootDatLen; //Number of bytes to read/write
DWORD BootAddr; //24 bit memory address (Prog or EE)
BYTE BytesPerBlock;
BYTE BytesPerAddr;
WORD MaxRetrys; //Number of retries before failure
} PIC;
我的:
public struct PIC
{
public byte BootCmd;//{ get; set; }
public byte BootDatLen ;//{ get; set; }
public ulong BootAddr ; //{ get; set; }
public byte BytesPerBlock; //{ get; set; }
public byte BytesPerAddr ; //{ get; set; }
public ushort MaxRetrys; //{ get; set; }
}