【问题标题】:C unsigned char ** and unsigned long * to C#C unsigned char ** 和 unsigned long * 到 C#
【发布时间】:2017-03-28 16:36:47
【问题描述】:

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

但是我的调用代码出现错误:“尝试读取或写入受保护的内存。这通常表明其他内存已损坏。”

我的声明是否有任何错误?任何解决此问题的想法将不胜感激。

【问题讨论】:

  • 您的代码有缺陷。尝试调试它。我们不能。我们甚至看不到它。
  • @Ðаn 我已经用 C# 代码更新了我的问题。这是一个自定义 dll,它没有在 pinvoke.net 上声明信息。

标签: c# pinvoke


【解决方案1】:

尝试关注:

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 long 是 32 位无符号的,uint 在 C# 中。你犯了我最初在outBuf 参数中指出的错误。还有更多的错误。我不会为你纠正它们。从好的方面来说,我很高兴你已经意识到这是多么有缺陷。
  • 肯定有内存泄漏。我在最后一条评论中所说的一切都是正确的。您是否想到您的 pinvoke 答案中的所有反对票都意味着什么?当你执行上面的代码时发生了什么?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-08-22
  • 2017-09-10
  • 1970-01-01
  • 2011-04-29
  • 2012-05-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多