未知模块中发生“System.AccessViolationException”类型的异常。尝试读取或写入受保护的内存

问题描述 投票:0回答:0

我创建了一个 c++ dll 并在项目中使用 [DllImport("dll")],而我在构建后使用此 dll,它在以下函数 AES_init_ctx() 处崩溃;

这是我的DLL代码:

“DLLCreation.h”

extern "C" __declspec(dllexport) void AES_init_ctx(struct AES_ctx* ctx, const uint8_t* key);
extern "C" __declspec(dllexport) void AES_ECB_encrypt(const struct AES_ctx* ctx, uint8_t* buf);

“DLLCreation.cpp”

// DLLCreation.cpp :定义 DLL 的导出函数。 //





DLLCREATION_API void AES_init_ctx(struct AES_ctx* ctx, const uint8_t* key)
{
    KeyExpansion(ctx->RoundKey, key);
}


DLLCREATION_API void AES_ECB_encrypt(const struct AES_ctx* ctx, uint8_t* buf)
{
    // The next function call encrypts the PlainText with the Key using AES algorithm.
    Cipher((state_t*)buf, ctx->RoundKey);
}




“程序.cs”

using System.Runtime.InteropServices;

class Program
{

    [StructLayout(LayoutKind.Sequential)]
    struct AES_ctx
    {
       public byte[] RoundKey;
        public byte[] Iv;

    };

    private const string dllPath = "C:\\Users\\RnD User\\source\\repos\\RizwanCodeDLL\\x64\\Debug\\DLLCreation.dll";
    [DllImport(dllPath,CallingConvention = CallingConvention.Cdecl)]
    //static extern void AES256(byte[] plain,byte[] key,byte[] cipher);
    static extern void AES_init_ctx(AES_ctx ctx, byte[] key);
    [DllImport(dllPath, CallingConvention = CallingConvention.Cdecl)]
    static extern void AES_ECB_encrypt(AES_ctx ctx, byte[] buf);

    static void Main(string[] args)
    {

        byte[] IV = { 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff }; //plaintext example
        byte[] key = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
        0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f}; 
        byte[] cipher = { };
       

        byte[] b = Program.MarshalUnsignedCharArray(IV,key);
        // Console.WriteLine(b);
    }

    public static byte[] MarshalUnsignedCharArray(byte[] IV, byte[] key)
    {
        AES_ctx ctx = new AES_ctx();
        ctx.RoundKey = new byte[240];
        ctx.Iv = new byte[16];
        AES_init_ctx(ctx, key);
        AES_ECB_encrypt(ctx,IV);
        return IV;
    }

}

我已经尝试了上面提到的过程。我已经创建了公共数组。我收到错误,这是我的标题。

c# memory dllimport access-violation protected
© www.soinside.com 2019 - 2024. All rights reserved.