[英]How to resolve Error external exception E0434352 on calling a C# dll method from Delphi
我需要解压缩大型 gzip 文件(超过 4.5 Go)。 我在使用 TDecompressionStream 使用 Delphi Seattle 执行此操作时遇到了一些麻烦(结果文件被截断)。
为了避免这个问题,我选择在 C# dll 中执行此任务并从 Delphi 调用它。
我的 C# 代码正在运行,我使用控制台应用程序对其进行了测试。 我添加了 nugget 包 UnmanagedExports 并以 32 位编译了 dll。
当我从 Delphi 调用我的 dll 方法时,出现此错误:“外部异常 E0434352”
我遵循此链接的建议: How to use a DLL created with C# in Delphi
但我已经有这个问题了
我的 C# 代码
static public class UnZip
{
[DllExport("UngzipFile", CallingConvention.StdCall)]
public static int UngzipFile(string aFile)
{
int result = 0;
FileInfo fileInfo = new FileInfo(aFile);
using (FileStream fileToDecompress = fileInfo.OpenRead())
{
string decompressedFileName = Path.Combine(Path.GetDirectoryName(aFile), "temp.sql");
using (FileStream decompressedStream = File.Create(decompressedFileName))
{
using (GZipStream decompressionStream = new GZipStream(fileToDecompress, CompressionMode.Decompress))
{
try
{
decompressionStream.CopyTo(decompressedStream);
}
catch
{
result = 1;
}
}
}
}
return result;
}
}
我的德尔福代码
function UngzipFile(aFile : string) : Integer; stdcall; external 'UnCompress.dll';
procedure TForm1.UnzipFile(aFileName: String);
var
UnZipFileName : string;
Return : integer;
DllZipFile : PWideChar;
begin
UnZipFileName := ExtractFilePath(aFileName)+'Temp.sql';
if FileExists(UnZipFileName) then
DeleteFile(UnZipFileName);
DllZipFile := PWideChar(aFileName);
Return := UngzipFile(DllZipFile);
if Return > 0 then
raise Exception.Create('Error while uncompressing file');
end;
目前,当我从 Delphi 调用 UngzipFile 时,_我有外部异常 E0434352。
我希望 result = 0 并且我的文件被解压缩。
谢谢你的帮助。
感谢鲁迪,我找到了解决方案。
由于字符串参数,我的 DLL 中出现异常。 我在 dll 中添加日志,我发现只有我的参数的第一个字符被 dll 占用。
这篇文章在 Delphi 中使用 C# DLL 仅使用第一个函数参数帮助我纠正我的代码。
新的 C# 代码
static public class UnZip
{
[DllExport("UngzipFile", CallingConvention.StdCall)]
public static int UngzipFile([MarshalAs(UnmanagedType.LPWStr)] string aFile)
{
if (!File.Exists(aFile))
return 3;
FileInfo fileInfo;
string logFile = @"D:\Temp\logDll.log";
try
{
File.AppendAllText(logFile, aFile);
fileInfo = new FileInfo(aFile);
}
catch(Exception ex)
{
File.AppendAllText(logFile, String.Format("File : {0} || Exception : {1}",aFile,ex.Message));
return 2;
}
int result = 0;
using (FileStream fileToDecompress = fileInfo.OpenRead())
{
string decompressedFileName = Path.Combine(Path.GetDirectoryName(aFile), "temp.sql");
using (FileStream decompressedStream = File.Create(decompressedFileName))
{
using (GZipStream decompressionStream = new GZipStream(fileToDecompress, CompressionMode.Decompress))
{
try
{
decompressionStream.CopyTo(decompressedStream);
}
catch
{
result = 1;
}
}
}
}
return result;
}
}
通过在我的参数声明中添加“[MarshalAs(UnmanagedType.LPWStr)]”,可以解决问题。
感谢鲁迪的帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.