托管C++嵌入C#

http://blog.csdn.net/csethcrm/article/details/18261331


使用托管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     else
26     {
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             else
19                 info.Invoke(null, null);
20             //Application.EnableVisualStyles();
21             //Application.SetCompatibleTextRenderingDefault(false);
22             //Application.Run(new Form1());
23         }
24     }
复制代码
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值