Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Create DLL in C# and call in Delphi XE6 [duplicate]

Tags:

c#

delphi

I created a DLL in VS2013 using File/New Project/Class Library. I then tried to load it dynamically in Delphi. But Delphiis returning NIL for procedure GetProcAddress.

My C# & Delphi code looks like what I have posted below. In the code GetProcAddress is returning NIL. Please advise if I am missing something.

C# Code

using System;
namespace TestDLL
{
    public class Class1
    {
        public static string EchoString(string eString)
        {
            return eString;
        }
    }
}

Delphi Code

 Type
    TEchoString = function (eString:string) : integer;stdcall;

  function TForm1.EchoString(eString:string):integer;
  begin
    dllHandle := LoadLibrary('TestDLL.dll') ;
    if dllHandle <> 0 then
    begin
      @EchoString := GetProcAddress(dllHandle, 'EchoString') ;
      if Assigned (EchoString) then
            EchoString(eString)  //call the function
      else
        result := 0;
      FreeLibrary(dllHandle) ;
    end
    else
    begin
      ShowMessage('dll not found ') ;
   end;
end;
like image 254
ary Avatar asked Jan 15 '15 16:01

ary


People also ask

What is DLL in C programming?

A DLL is a library that contains code and data that can be used by more than one program at the same time. For example, in Windows operating systems, the Comdlg32 DLL performs common dialog box related functions. Each program can use the functionality that is contained in this DLL to implement an Open dialog box.

How are DLL files created C#?

To create a DLL File, click on New project, then select Class Library. Enter your code into the class file that was automatically created for you and then click Build Solution from the Debug menu. P.S. DLL files cannot be run just like normal applciation (exe) files.


1 Answers

A C# DLL is a managed assembly and does not export its functionality via classic PE exports. Your options:

  1. Use C++/CLI mixed mode to wrap the C#. You can then export functions in unmanaged mode in the usual way.
  2. Use Robert Giesecke's UnmanagedExports. This is perhaps more convenient than a C++/CLI wrapper.
  3. Expose the managed functionality as a COM object.

Once you get as far as choosing one of these options you will have to deal with your misuse of the string data type. That's a private Delphi data type that is not valid for interop. For the simple example in the question PWideChar would suffice.

like image 136
David Heffernan Avatar answered Sep 27 '22 21:09

David Heffernan