C # managed code and C + + unmanaged code are called one another (C # calls C + + code &.net code security)

Source: Internet
Author: User

In recent projects, project source code confidentiality issues are involved, because the code is written in C #, easy to decompile, so the decision to extract the core algorithm part of the use of C + + writing, C + + so far seems to have not been very good decompile, of course, if you are a disassembly master, perhaps it is possible to decompile. This means that C # managed code and C + + unmanaged code call each other, and then we investigate some of the information and share

A. Static call C + + dynamic link in C #

1. VC Project Cppdemo, the establishment of the time to select Win32 Console (DLL), select the DLL.

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

extern "C" __declspec(dllexport) int Add(int a,int b)
{

     return a+b;
}

3. Compile the project.

4. Create a new C # project, select Console application, set up test program Interopdemo

5. Add references in Program.cs: using System.Runtime.InteropServices;

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

using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;

namespace InteropDemo
{
    class Program
    {
        [DllImport("CppDemo.dll", EntryPoint = "Add", ExactSpelling = false, CallingConvention = CallingConvention.Cdecl)]
        public static extern int Add(int a, int b); //DllImport请参照MSDN

        static void Main(string[] args)
        {
            Console.WriteLine(Add(1, 2));
            Console.Read();
        }
    }
}

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

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.