我根据别人写的用vb调用的代码,进行改装到c#里面,但是会报以下异常:
Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
vb代码如下:
Private
Declare
Sub CopyMemory()
Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (hpvDest As Any, hpvSource As Any, ByVal cbCopy As Long)
Private Declare Function Compress()Function Compress Lib "zlibwapi.dll" Alias "compress" (dest As Any, destLen As Any, src As Any, ByVal srcLen As Long) As Long
Private Declare Function uncompress()Function uncompress Lib "zlibwapi.dll" (dest As Any, destLen As Any, src As Any, ByVal srcLen As Long) As Long
Private Const OFFSET As Long = &H8
Private Sub Form_Load()Sub Form_Load()
Dim a() As Byte
Dim b() As Byte
Dim i As Integer
ReDim a(0 To 256) As Byte
ReDim b(0 To 256) As Byte
For i = 0 To 256
a(i) = i Mod 10
b(i) = i Mod 10
Next
CompressByte a, b
MsgBox UBound(a) + 1
End Sub
'压缩数组
Public Function CompressByte()Function CompressByte(ByteArray() As Byte, ByteArray2() As Byte) As Boolean
Dim BufferSize As Long
Dim TempBuffer() As Byte
'Create a buffer to hold the compressed data
BufferSize = UBound(ByteArray) + 1
BufferSize = BufferSize + (BufferSize * 0.01) + 12
ReDim TempBuffer(BufferSize)
'Compress byte array (data)
CompressByte = (Compress(TempBuffer(0), BufferSize, ByteArray(0), UBound(ByteArray) + 1) = 0)
'Add the size of the original data
Call CopyMemory(ByteArray(0), CLng(UBound(ByteArray) + 1), OFFSET)
'Remove redundant data
ReDim Preserve ByteArray(0 To BufferSize + OFFSET - 1)
CopyMemory ByteArray(OFFSET), TempBuffer(0), BufferSize
Dim newByteArray() As Byte
ReDim newByteArray(0 To BufferSize + OFFSET - 1)
Dim i As Integer
For i = 0 To OFFSET
newByteArray(i) = TempBuffer(CLng(UBound(ByteArray) + 1) + i)
Next
End Function
c#代码如下:
[DllImport(
"
kernel32.dll
"
)]
public
unsafe
static
extern
void
CopyMemory(IntPtr hpvDest, IntPtr hpvSource,
int
cbCopy);
[DllImport(
"
zlibwapi.dll
"
)]
public
unsafe
static
extern
int
compress(IntPtr dest,
int
destLen, IntPtr src,
int
srcLen);
[DllImport(
"
zlibwapi.dll
"
)]
public
unsafe
static
extern
int
uncompress(IntPtr dest,
int
destLen, IntPtr src,
int
srcLen);
private
const
long
OFFSET
=
8
;
private
void
button2_Click(
object
sender, EventArgs e)
{
aa();
}
private
unsafe
void
aa()
{
int len = 10 * 1024;
byte[] data = new byte[len];
Random rnd = new Random(255);
for (int i = 0; i < len; i++)
{
data[i] = (byte)(int)(i / 45);
}
long len1 = data.Length;
long len2 = len1+(int)(len1*0.01)+12;
byte[] data2 = new byte[len2];
IntPtr dest;
IntPtr src;
fixed (byte* b_src = &data[0])
{
fixed (byte* b_dest = &data2[0])
{
src = (IntPtr)b_src;
dest = (IntPtr)b_dest;
//问题处在此处
compress(dest, len2, src, len1);
//
}
}
}