zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    ubuntu 升级到5.1kernel,打开bbr
    python json.loads json.dumps的区别
    centos7 install vim8
    Linux的Network Tunnel技术
    Linux内核网络数据包处理流程
    CAD2010 破解方法
    [原创]MSP430FR4133练习(一):GPIO输入电平状态判断
    [原创] Xinput_1.3.DLL / MSVCR100.DLL文件缺失解决办法
    [原创]找不到mswinsck.ocx的解决办法
    Windows7系统推荐
  • 原文地址:https://www.cnblogs.com/silva/p/191552.html
Copyright © 2011-2022 走看看