C#Managed 程式碼與C++Unmanaged 程式碼互相調用一(C#調用C++代碼&.net 代碼安全)

來源:互聯網
上載者:User

在最近的項目中,牽涉到項目原始碼保密問題,由於代碼是C#寫的,容易被反編譯,因此決定抽取核 心演算法部分使用C++編寫,C++到目前為止好像還不能被很好的反編譯,當然如果你是反組譯碼高手的話,也 許還是有可能反編譯。這樣一來,就涉及C#Managed 程式碼與C++Unmanaged 程式碼互相調用,於是調查了一些資料, 順便與大家分享一下

一. C# 中靜態調用C++動態連結

1. 建立VC工程CppDemo,建立的時候選擇Win32 Console(dll),選擇Dll。

2. 在DllDemo.cpp檔案中添加這些代碼。

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

     return a+b;
}

3. 編譯工程。

4. 建立新的C#工程,選擇Console應用程式,建立測試程式InteropDemo

5. 在Program.cs中添加引用:using System.Runtime.InteropServices;

6. 在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();
        }
    }
}

好了,現在您可以測試Add程式了,是不是可以在C# 中調用C++動態連結了,當然這是靜態調用,需要 將CppDemo編譯產生的Dll放在DllDemo程式的Bin目錄下

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.