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

來源:互聯網
上載者:User
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

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.