简体   繁体   中英

Access violation calling C# dll function from Delphi XE6

After migrating our project from Delphi 2007 to XE6, we are no longer able to properly call an exported function in a C# dll we built. The C# code seems to execute fine, and does what it's supposed to do, but after it's done, it throws an access violation.

The code:

Result := False;

  lib := LoadLibrary('KJPDFExport.dll');
  if lib = 0 then RaiseLastOSError;
  try
    try
      @prc := GetProcAddress(lib, 'ExportOffice');
      if Assigned(prc) then
      begin
        Result := prc(sourceFile,
            ChangeFileExt(destinationFile, ''),
            pdfBackgroundHeadFile,
            pdfBackgroundSubFile);
      end
      else
        ShowMessage('ExportOffice not found in KJPDFExport.dll');
    except
      on e:Exception do
      begin
        ShowMessage(e.Message);
      end;
    end;
  finally
    FreeLibrary(lib);
  end;

The strings I am passing to the C# function are all AnsiStrings. They used to be just "string" in the 2007 version of the project, and I have thus changed them to AnsiString.

I am baffled, I have been looking for hours and can't find the problem.

It turns out it worked all along.. The Delphi debugger doesn't know how to handle C# exceptions. Even when you have a try/catch statement around your throw in C#, the Delphi debugger will still see it as an access violation. When you simply just press continue it works. The reason for the crash was another piece of code that had to be converted to use AnsiString.

Did your try to use local ansiString variable ? ChangeFileExt() return String value.

Somthing like that :

var sIn, sOut : ansiString;
  Result := False;

  sIn  := ansiString(sourceFile);
  sOut := ansistring(ChangeFileExt(destinationFile, ''));

  lib := LoadLibrary('KJPDFExport.dll');
  if lib = 0 then RaiseLastOSError;
  try
    try
      @prc := GetProcAddress(lib, 'ExportOffice');
      if Assigned(prc) then
      begin
        Result := prc(Sin,
                      sOut,
            pdfBackgroundHeadFile,
            pdfBackgroundSubFile);
      end
      else
        ShowMessage('ExportOffice not found in KJPDFExport.dll');
    except
      on e:Exception do
      begin
        ShowMessage(e.Message);
      end;
    end;
  finally
    FreeLibrary(lib);
  end;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM