[英]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.