使用託管C++調用C#的exe程式

來源:互聯網
上載者:User

使用託管C++調用C#的exe程式。

(事後證明是對Reflector是無效的。)哎。

添加CLR控制台應用程式。把C#的exe程式放到“資源檔”檔案夾下,右鍵屬性的項類型設定為已編譯的託管資源。

在主程式碼的main函數改寫為如下內容:

 1 // x.cpp: 主專案檔案。 2  3 #include "stdafx.h" 4  5 using namespace System; 6  7 [STAThreadAttribute] 8 int main(array<System::String ^> ^args) 9 {10     System::Reflection::Assembly^ a;11     a = System::Reflection::Assembly::GetExecutingAssembly();12     System::IO::Stream ^ stream;13     stream = a->GetManifestResourceStream("csharp.exe");14     array<System::Byte> ^ bs = gcnew array<System::Byte>(stream->Length);15     stream->Read(bs, 0, (int)(stream->Length));16     System::Reflection::Assembly^ exe;17     exe = System::Reflection::Assembly::Load(bs);18     System::Reflection::MethodInfo^ info;19     info = exe->EntryPoint;20     array<System::Reflection::ParameterInfo^ > ^ parameters = info->GetParameters();21     if ((parameters != nullptr) && (parameters->Length > 0))22     {23         info->Invoke(nullptr, (array<System::Object ^ > ^) args);24     }25     else26     {27         info->Invoke(nullptr, nullptr);28     }29     return 0;30 }

 其對應的C#版代碼如下:

 1     static class Program 2     { 3         /// <summary> 4         /// 應用程式的主進入點。 5         /// </summary> 6         [STAThread] 7         static void Main(string[] args) 8         { 9             var asm = Assembly.GetExecutingAssembly();10             Stream stream = asm.GetManifestResourceStream("csharp.exe");11             byte[] bs = new byte[stream.Length];12             stream.Read(bs, 0, (int)stream.Length);13             var exe = Assembly.Load(bs);14             MethodInfo info = exe.EntryPoint;15             ParameterInfo[] parameters = info.GetParameters();16             if ((parameters != null) && (parameters.Length > 0))17                 info.Invoke(null, (object[])args);18             else19                 info.Invoke(null, null);20             //Application.EnableVisualStyles();21             //Application.SetCompatibleTextRenderingDefault(false);22             //Application.Run(new Form1());23         }24     }

 

聯繫我們

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