C unsigned char ** 和 unsigned long * 到 C#

C unsigned char ** and unsigned long * to C#

我正在尝试从 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);

但是我的调用代码出错了:"Attempted to read or write protected memory. This is often an indication that other memory is corrupt."

我的申报有错吗?任何纠正此问题的想法将不胜感激。

尝试以下:

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