我试图用C#调用用C编写的外部DLL函数,这是来自C的DLLEXPORT代码:
DLLEXPORT int DLLCALL Compress(int compressLevel, const unsigned char *srcBuf, unsigned char **outBuf, unsigned long *Size);
这是我从C#调用该函数的代码:
[DllImport("test.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern int Compress(int compressLevel, ref byte[] srcBuf, ref byte[] outBuf, Uint64 size);
...
byte[] buffer = new byte[1000];
byte[] _compressedByteArray = null;
Uint64 OutSize = 0;
Compress(10, buffer , compressedByteArray, OutSize);
然而,我的调用代码出错:"尝试读取或写入受保护的内存。这通常表明其他内存已损坏。"
我的声明是否有任何错误?任何纠正这个问题的想法都会非常感激。
答案 0 :(得分:-3)
尝试以下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
namespace ConsoleApplication49
{
class Program
{
[DllImport("XXXXX.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern int Compress(int compressLevel, IntPtr srcBuf, IntPtr outBuf, IntPtr size);
static void Main(string[] args)
{
int compressLevel = 0;
string input = "The quick brown fox jumped over the lazy dog";
IntPtr srcBuf = Marshal.StringToBSTR(input);
IntPtr outBuf = IntPtr.Zero;
IntPtr size = Marshal.AllocHGlobal(sizeof(long));
int results = Compress(compressLevel, srcBuf, outBuf, size);
string output = Marshal.PtrToStringAnsi(outBuf);
long longSize = Marshal.ReadInt64(size);
}
}
}