首页 > 解决方案 > 如何在c#中使用c字节指针函数的dll?

问题描述

我有一个 dll 库,就像

void Decrypt(BYTE* RoundKey, BYTE* Data){...}

它是一个简单的解密函数,它接收密钥和数据指针并仅解密数据。我想在 C# 中使用这个 dll,所以我写了一个示例测试代码

[DllImport("test.dll", CallingConvention = CallingConvention.Cdecl)]
extern private static unsafe void decrypt(byte* RoundKey, byte* Data);

static unsafe void Main(string[] args) {
   public static byte[] Key = {0x00, ....};
   public static byte[] data = {0x00, ....};
   decrypt(&Key, &data);
}

而且这段代码没有编译。我想知道如何在 C# 中使用这个 dll?

标签: c#.netpointersdll

解决方案


只需按如下方式编写(假设 dll 库知道密钥和数据大小):

[DllImport("test.dll", CallingConvention = CallingConvention.Cdecl)]
private static unsafe extern void Decrypt(byte* roundKey, byte* data);

public static byte[] Key = { 0x00, ...};
public static byte[] Data = { 0x00, ... };

static unsafe void Main(string[] args)
{
       fixed (byte* keyPtr = Key)
       {
              fixed(byte* dataPtr = Data)
              {
                    Decrypt(keyPtr, dataPtr);
              }
       }
}

推荐阅读