将C unsigned char **和unsigned long *转换为C# [英] C unsigned char ** and unsigned long * to C#

查看:212
本文介绍了将C unsigned char **和unsigned long *转换为C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从C#调用用C编写的外部DLL函数,这是C的DLLEXPORT代码:

I'm trying to call an external DLL function written in C from C#, this is the DLLEXPORT code from C:

DLLEXPORT int DLLCALL Compress(int compressLevel, const unsigned char *srcBuf, unsigned char **outBuf, unsigned long *Size);

这是我从C#调用该函数的代码:

This is my code from C# to call that function:

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

但是我的调用代码遇到了一个错误:试图读取或写入受保护的内存.这通常表明其他内存已损坏."

However my calling code got an error : "Attempted to read or write protected memory. This is often an indication that other memory is corrupt."

我的声明有误吗?任何纠正此问题的想法将不胜感激.

Did I make any mistake on my declaration? Any idea to correct this issue would be very appreciate.

推荐答案

尝试以下操作:

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

这篇关于将C unsigned char **和unsigned long *转换为C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆