3
votes

For testing I am trying to call a Delphi XE2 DLL (see code) in a C# application (developed in Visual C# 2010 Express).

procedure CLP; stdcall; export;
begin
  showmessage('TEST');
end;

exports CLP;

However when trying to add the DLL as reference to a C# project the following message appears:

A reference to 'D:\temp\test.dll' could not be added. Please make sure that the file is accessible, and that is a valid assembly or COM component.

When the same DLL is compiled under Delphi 2010 it works without any problem.

Any suggestions how to solve the problem are appreciated.

3
you've never accepted an answer here, or voted. I respectfully request that you read the faq and learn about these important parts of Stack Overflow.David Heffernan

3 Answers

6
votes

You cannot add an unmanaged DLL to a .NET project.

But you can import the functions, see for instance Platform Invoke Tutorial

3
votes

You are trying to link to an unmanaged, native DLL. You cannot add such a thing to a managed application as a reference.

The way to call your DLL is to use p/invoke:

[DllImport(@"test.dll", CallingConvention=CallingConvention.Stdcall)]
static extern void CLP();

Naturally things can get a bit more complicated when you start having parameters to your DLL but you can go a very long way with p/invoke.

One thing you need to watch out for is that your managed project targets x86 if your DLL is 32 bit, or x64 if your DLL is 64 bit.

As a final, minor, note the use of export is pointless in modern Delphi. You should simply remove it since the compiler ignores it anyway.

0
votes

Henk is right and I want to add a few things.

First of all, You can add a dll only if it is a .NET managed dll(which calls assembly). But you can import unmanged functions from unmanaged dll or exe files. So the right question is how I can import functions from unmanaged dll, and you should seek the answer for it. And I think the best start position is pinvoke website.