How to import dll in c# that can be accessed by [DllImport]


The steps are as follows:

1. Compile your C# DLL (You may use Visual Studio for this).
2. Decompile your C# DLL using ILDASM.EXE.
3. Expose/Export your methods (Details to follow).
4. Recompile your C# DLL from the modified MSIL code using ILASM.


Here is a walk-through:

1. Compile the following code as a C# (.NET) DLL (Release).  This method returns 0 if the string supplied has a length equal to the integer x supplied.

  namespace ExpertsExchange.Q20919344
  {
    public class Email
    {
      public static int Test(int x, string y)
      {
        try
        {
          if(x==y.Length)
            return 0;
          else
            return 1;
        }
        catch
        {
          return 0;
        }
      }
    }
  }


2. Start the Visual Studio command prompt and go to the Release directory for your project.  Enter, "ildasm Email.dll /out:Email.il" on the command line.  You should see as "// WARNING: Created Win32 resource file Email.res" message.

3. Enter, "notepad Email.il" on the command line.

4. In the IL file,
  a) Find the following line of code:

  .corflags 0x00000001

   and replace it with:

  .corflags 0x00000002
  .data VT_01 = int32[1]
  .vtfixup [1] int32 fromunmanaged at VT_01

  b) After the following code:

  .method public hidebysig static int32 Test(int64 x, string y) cil managed
  {

  Enter,

  .vtentry 1:1
  .export [1] as Test

5. Save and exit notpad. Return to the command prompt window.

6. At the command line type, "ilasm /dll Email.il /res:Email.res /out:Email.dll".  You should see:

  Assembling 'Email.il' , no listing file, to DLL --> 'Email.dll'
  Source file is ANSI

  Assembled method Email::Test
  Assembled method Email::.ctor
  Creating PE file

  Emitting members:
  Global
  Class 1 Methods: 2;
  EmitExportStub: dwVTFSlotRVA=0x00000000
  Writing PE file
  Operation completed successfully

7. You can now call this DLL using DllImport in .NET, or from another Win32 DLL/Application.

  eg:
  //TODO: Supply correct path to "Email.dll"
  [System.Runtime.InteropServices.DllImport(@"Email.dll", EntryPoint="Test")]
  static extern int Email_Test(int x, string y);

  Email_Test(10, "abcdefghij") //Returns 0
  Email_Test(10, "abcdefghi") //Returns 1
posted @ 2005-07-12 18:00  Ready!  阅读(1984)  评论(4编辑  收藏  举报