簡體   English   中英

在 C++ Dll 中創建方法以導入 C#

[英]Creating methods within a C++ Dll to import into C#

在參加了一些小型課程並使用了 WPF 和 C# 之后,我決定重寫我一直在研究的應用程序。 我在 C++ DLL 創建並導入到我的 WPF 應用程序中的大多數功能都可以完美運行。

不過,我對他們中的一些人有點麻煩。 我以前從其他函數傳遞變量或使用對話和消息框的地方。

這是我需要放入 DLL 的 C++ 函數之一的示例。 function 生成使用 OpenFileDialog 添加到列表框中的文件列表的 MD5 hash 代碼。

array<Byte>^ Hash()
{
    array<Byte>^ Buffer = nullptr;
    int x = 0;
    for each(String^ Files in listBox2->Items)
    {
        try
        {
            IO::FileStream^ FileStream = gcnew IO::FileStream(Files, IO::FileMode::Open, IO::FileAccess::Read);

            IO::BinaryReader^ BinaryReader = gcnew IO::BinaryReader(FileStream);

            IO::FileInfo^ FileInfo = gcnew IO::FileInfo(Files);

            System::Int64 TotalBytes = FileInfo->Length;

            Buffer = BinaryReader->ReadBytes(safe_cast<System::Int32>(TotalBytes));

            FileStream->Close();
            delete FileStream;
            BinaryReader->Close();

            MD5^ md5 = gcnew MD5CryptoServiceProvider;

            array<Byte>^ Hash = md5->ComputeHash(Buffer);

            String^ FileHex = BitConverter::ToString(Hash);

            listBox3->Items->Add(FileHex);

            x = x + 1;
        }
        catch(Exception^ e)
        {
            MessageBox::Show(e->Message->ToString());
            listBox1->Items->RemoveAt(listBox1->SelectedIndex);
        }
    }
    return Buffer;
}

此代碼在我制作的 C++ 應用程序中完美運行。 所以我試圖做的是把 try 語句中的所有內容都用作方法的代碼,但是我的問題來自第一行,顯然“文件”是一個變量,或者至少我認為這是問題所在。

有沒有辦法我仍然可以按原樣使用此代碼並在 C# 中創建一個變量,然后將其傳遞給此方法?

我嘗試在我的 C# 應用程序中使用以下代碼

private void button2_Click(object sender, RoutedEventArgs e)
{
    DllTest.Funtions Functions = new DllTest.Funtions();

    foreach (String Files in listBox1.Items)
    {
        String File = Files;
        File = Functions.HashFunction();

        listBox2.Items.Add(File);
    }
}

但是,當我運行應用程序時,我只會得到列表框中出現的捕獲消息。 這是我使用方法“在 mscorlib.dll 中發生'System.ArgumentNullException'類型的第一次機會異常”方法時編譯器中的錯誤

無論如何我可以在不重寫 C# 中的方法的情況下做到這一點嗎?

抱歉,如果我的代碼不是最好的,我對 C++ 和 C# 還是很陌生

咨詢我的通靈調試器,我確定您希望在 C++/CLI 中使用它:

    String^ HashFunction(String^ filename)
    {
        array<Byte>^ Buffer = IO::File::ReadAllBytes(filename);
        array<Byte>^ Hash = MD5CryptoServiceProvider().ComputeHash(Buffer);
        return BitConverter::ToString(Hash);
    }

這在 C# 中:

private void button2_Click(object sender, RoutedEventArgs e)
{
    foreach (String filename in listBox1.Items)
    {
        try {
            listBox2.Items.Add(Functions.HashFunction(filename));
        }
        catch (Exception ex) {
            MessageBox.Show(e.Message);
        }
    }
}

但是我的通靈調試器經常出現故障。

String File = Files;
File = Functions.HashFunction();

上面的代碼沒有任何意義。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM