Accessing C# unmanaged exports from Delphi application

时间:2015-09-01 22:06:09

标签: c# delphi dll dllexport

I am using Robert Giesecke's Unmanaged Exports to put some methods from a C# class into a DLL. For now, the code is:

[DllExport("add", CallingConvention = CallingConvention.StdCall)]
public static int TestExport(int left, int right)
{
    return left + right;
}

which is the same as Giesecke's sample code, aside from the CallingConvention but I've also tried it with Cdecl).

I'm trying to access this method in my Delphi VCL WinForms application. I'm following this article that is talking about exporting from a Delphi DLL and using the function in a Delphi console application. I may be wrongfully assuming too many similarities here.

Anyway, there are two notes:

1) Using GExperts's PE Information on that DLL (exported from a C# project) lists no exports. Seeing as this tool shows the entry points for the available exports, this to me is red flag #1. I didn't check Dependency Walker.

2) The Delphi article says to add the function declaration, then shows an example. My IDE doesn't like that syntax. This may be an application vs. console difference.

const
  TestExportsDLL = 'CS_CallbackTest_Class.dll';
type
  TForm1 = class(TForm)
...

  private
    function AddIntegers(_a, _b: integer): integer; stdcall; external TestExportsDLL;     
  public
    { Public declarations }
  end;

I've tried with a few different variations on this. Assuming using RGiesecke.DllExport is the best way to do this, why can't I get the Delphi application to compile?

1 个答案:

答案 0 :(得分:1)

Hard to know why the function isn't being exported. You didn't describe the steps you took to make the DLL. UnmanagedExports does work though. Follow the documented steps very carefully. One possible clue can be found in the documentation you linked to:

The task will only execute when you have selected a specific CPU target (x86, x64, Itanium) in your build option.

Until you get a DLL that exports your function there's not much point continuing to the Pascal code.

Your importing code is confused. An external function has to be declared at unit scope. A complete program to import looks like this:

{$apptype console}

const
  dllname = '...'; // replace this with the actual name

function add(left, right: Integer): Integer; stdcall; external dllname;

begin
  Writeln(add(42, 624));
  Readln;
end.