c# - 从 C# 调用 C++ dll 函数时出现问题

标签 c# c++ function dll interop

这是我关于 C# 中的河豚问题的第 3 个线程。尽管我无法在我的应用程序中实现河豚,但我决定将其用作外部 C++ dll。 请注意,我已经尝试过 Blowfish.NET 和任何其他程序,问题是我正在将代码从 C++ 转换为 C#,而 C# 代码必须与 C++ 代码完全相同。

到目前为止:

--->C++ DLL source<---

注意导出的函数在代码的末尾

C#代码(定义)

    [DllImport("TestDLL.dll", EntryPoint = "Initkey" ,ExactSpelling = true , CallingConvention = CallingConvention.Cdecl)]
    public static unsafe extern void Initkey(byte[] key);

    [DllImport("TestDLL.dll", EntryPoint = "encode", ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
    public static unsafe extern void encode(UInt32 *stream);

C#代码(函数调用)

-初始化河豚 key

UInt32[] keyarray = new UInt32[2];
//some code
Extern.Initkey(Misc.ConvertFromUInt32Array(keyarray));
//
//
//Helper function used to convert a UInt32 array into Byte array.
public static byte[] ConvertFromUInt32Array(UInt32[] array)
{
    List<byte> results = new List<byte>();
    foreach (UInt32 value in array)
    {
        byte[] converted = BitConverter.GetBytes(value);
        results.AddRange(converted);
    }
    return results.ToArray();
}

-编码数据。

            UInt32[] keyarray2 = new UInt32[2];
            //some code
            unsafe
            {
                fixed (UInt32* LPBYTE = keyarray2)
                {
                    Extern.encode(LPBYTE);
                }
            }

在 keyarray2 被 Encode 函数覆盖后,我通过解密检查 C++ 代码中的值以确保一切正常。

嗯,不行。那是我的问题,这就是为什么我向你寻求帮助。

我解密的时候是不同的,但是如果我在C++源码中加密和解密,它们是相等的。C++代码完全一样,只是没有DLL,因为代码是C++的。

可能是因为 Initialize 函数。几个月前我读到 C++ 中的数组作为指针传递。我不相信,但即便如此 - 这会是问题所在吗?

我找不到线索。我用 C# 中的那个河豚浪费了我的生命。至少该解决方案应该有效,但它不起作用 - 为什么?

最佳答案

要补充 jachymko 所说的内容,还请查看 BitConverter 的文档 - 您需要确保以您想要的字节顺序传递 key 和数据。 注意 - 在您之前的线程中,我使用修改后的 Blowfish.NET 加密器成功加密了数据,并使其与您的 C++ 代码的结果相匹配。

关于c# - 从 C# 调用 C++ dll 函数时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/695419/

相关文章:

c++ - 为什么允许 C++ 类具有零数据成员?

c# - 类中的属性/方法占用内存空间吗?

function - 理解 Haskell 中的函数定义和类型

python - 自动执行 Google Play 搜索列表中的项目

c# - 使用 LINQ 选择一行中的多个元素

c# - 翻译 "Multilanguage"枚举 javascript/c#

C++ Windows 凭据提供程序进度屏幕

c++ - 在新的 Qt SDK 中,我得到 <QtInstallationDir>\QtSDK\QtCreator\lib\qtcreatorcdbext32\qtcreatorcdbext.dll 找不到错误

c# - 使用Graph API获取用户信息

c# - 如何将接口(interface)作为参数传递给方法?