我需要解压缩大的gzip文件(超过4.5 Go)。在使用TDecompressionStream (结果文件被截断)时,我在使用Delphi Seattle时遇到了一些麻烦。
为了避免这个问题,我选择在Delphi中完成这个任务,并从C#调用它。
我的C#代码工作正常,我用一个控制台应用程序对它进行了测试。我添加了块金包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;
}
}
我的Delphi代码
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,并且我的文件是解压缩的。
谢谢你的帮助。
发布于 2019-03-29 17:12:57
多亏了鲁迪,我找到了解决方案。
由于字符串参数的原因,我的DLL中有一个异常。我在dll中添加了log,我发现只有我的参数的第一个字符是由dll获取的。
这篇文章Using a C# DLL in Delphi only uses the first function parameter帮助我纠正我的代码。
新的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)“,解决了这个问题。
塔克斯·鲁迪谢谢你的帮助。
https://stackoverflow.com/questions/55412331
复制相似问题