Static calls in C # C++dll and C # in dynamic call C++dll

Source: Internet
Author: User

Static calls in C # C++dll and C # in dynamic call C++dll

In recent projects, involving the project source code security issues, because the code is written in C #, easy to be anti-compilation, so decided to extract the core algorithm is written in C + +, C + + so far seems not to be very good anti-compilation, of course, if you are an anti-assembly master, it may be possible to decompile. In this way, it involves invoking C # managed code with C + + unmanaged code, and then investigating some of the information and sharing it with you:

I. Static calls to C + + dynamic links in C #

1. Establish VC project Cppdemo, set up the time to choose Win32 Console (DLL), select the DLL.

2. Add the code in the DllDemo.cpp file.

code
extern Span style= "Color:rgb (128, 0, 0); >c "  __declspec ( dllexport)   int  add ( int  a, int  b "
{
    
       a + b;
}

3. Compile the project.

4. Create a new C # project, select the console application, and set up a test program Interopdemo
5. Add references in Program.cs: using System.Runtime.InteropServices;

6. Add the following code to the Pulic class program:

Code
usingSystem;
usingSystem.Collections.Generic;
usingSystem.Text;
usingSystem.Runtime.InteropServices;

namespaceInteropdemo
{
classProgram
{
[DllImport ("CppDemo.dll", EntryPoint= "ADD", ExactSpelling= false, CallingConvention=callingconvention.cdecl)]
Public Static extern intAdd (intA,intb); //dllimport please refer to MSDN

Static voidMain (string[] args)
{
Console.WriteLine (Add (1, 2));
Console.read ();
}
}
}

OK, now you can test the add program, is not able to invoke C + + dynamic link in C #, of course, this is a static call, you need to put the Cppdemo compiled DLL in the Dlldemo program's Bin directory

two. Dynamic call C + + dynamic link in C #

In the first section, we talked about static calls to C + + dynamic links, due to DLL path constraints, not very convenient to use, C # We often through the configuration of dynamic call managed DLLs, such as some common design patterns: Abstract Factory, Provider, Strategy mode and so on, then is it possible to dynamically invoke C + + dynamic link? As long as you remember in C + +, through LoadLibrary, GetProcess, freelibrary These functions can be dynamically called dynamically linked (they are included in the Kernel32.dll), then the problem solved, we step by step experiment

1. Encapsulate several methods in KERNEL32 to call the class Nativemethod

Code
usingSystem;
usingSystem.Collections.Generic;
usingSystem.Text;
usingSystem.Runtime.InteropServices;

namespaceInteropdemo
{
Public Static classNativemethod
{
[DllImport ("Kernel32.dll", EntryPoint= "LoadLibrary")]
Public Static extern intLoadLibrary (
[MarshalAs (UNMANAGEDTYPE.LPSTR)]stringlplibfilename);

[DllImport ("Kernel32.dll", EntryPoint= "GetProcAddress")]
Public Static externIntPtr GetProcAddress (inthmodule,
[MarshalAs (UNMANAGEDTYPE.LPSTR)]stringlpprocname);

[DllImport ("Kernel32.dll", EntryPoint= "FreeLibrary")]
Public Static extern BOOLFreeLibrary (inthmodule);
}
}

2. Use the Nativemethod class to dynamically read C++dll, obtain a function pointer, and encapsulate the pointer as a delegate in C #. The reason is simple, there is no use of pointers in C #, as follows
int hmodule = Nativemethod.loadlibrary (@ "C:" CppDemo.dll ");

IntPtr IntPtr = nativemethod.getprocaddress (hmodule, "Add");

For details, see the code

Code
usingSystem;
usingSystem.Collections.Generic;
usingSystem.Text;
usingSystem.Runtime.InteropServices;

namespaceInteropdemo
{
classProgram
{
//[DllImport ("CppDemo.dll", EntryPoint = "Add", ExactSpelling = False, CallingConvention = callingconvention.cdecl)]
//public static extern int Add (int a, int b);//dllimport please refer to MSDN


Static voidMain (string[] args)
{
//1. Dynamically loading C + + DLLs
            inthmodule=Nativemethod.loadlibrary (@"C:\CppDemo.dll");
if(hmodule== 0) return;

//2. Reading function pointers
IntPtr IntPtr=nativemethod.getprocaddress (hmodule,"ADD");

//3. Encapsulate a function pointer as a delegate
ADD addfunction=(ADD) marshal.getdelegateforfunctionpointer (INTPTR,typeof(ADD));

//4. Testing
Console.WriteLine (AddFunction (1, 2));
Console.read ();
}

/// <summary>
///function pointers
/// </summary>
/// <param name= "a" ></param>
/// <param name= "B" ></param>
/// <returns></returns>
        Delegate intAdd (intA,intb);

}
}

With two examples, we can invoke C + + code in C # dynamically or statically.

Transferred from: http://www.cnblogs.com/Jianchidaodi/archive/2009/03/09/1407270.html

Static calls in C # C++dll and C # in dynamic call C++dll

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.