现在的位置: 首页 > 综合 > 正文

NativeC++通过CLI调用C#的Form

2018年03月19日 ⁄ 综合 ⁄ 共 2719字 ⁄ 字号 评论关闭

一 调用方法

      Native C++的project调用C#的DLL,一般有3中方法:
      1)通过COM封装
      2)通过CLI/C++的Wrapper
      3)  在VS中可以直接修改NativeC++的project或是部分文件为使用CLR来调用C#的DLL

二 实例
1)C#的一个MyForm类,有public函数ShowMyForm()

using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;

namespace CsharpDLL
{
    
public class MyForm : Form
    
{
        
private Button button1;

        
public void ShowMyForm()
        
{
            
this.ShowDialog();
        }

        
public MyForm()
        
{
            InitializeComponent();
            
this.Text = "MyForm";
            
this.StartPosition = FormStartPosition.CenterScreen;
        }

        
private void InitializeComponent()
        
{
            
this.button1 = new System.Windows.Forms.Button();
            
this.SuspendLayout();
            
// 
            
// button1
            
// 
            this.button1.Location = new System.Drawing.Point(11074);
            
this.button1.Name = "button1";
            
this.button1.Size = new System.Drawing.Size(7523);
            
this.button1.TabIndex = 0;
            
this.button1.Text = "TestMessageBox";
            
this.button1.UseVisualStyleBackColor = true;
            
this.button1.Click += new System.EventHandler(this.button1_Click);
            
// 
            
// MyForm
            
// 
            this.ClientSize = new System.Drawing.Size(292266);
            
this.Controls.Add(this.button1);
            
this.Name = "MyForm";
            
this.ResumeLayout(false);

        }


        
private void button1_Click(object sender, EventArgs e)
        
{
            MessageBox.Show(
"Hello, i am a Csharp Form!");
        }

    }

}

2)C#的exe调用

using System;
using System.Collections.Generic;
using System.Text;

namespace CsharpTest
{
    
class Program
    
{
        
static void Main(string[] args)
        
{
            System.Console.WriteLine(
"Csharp main funtion start:");
            CsharpDLL.MyForm myForm 
= new CsharpDLL.MyForm();
            myForm.ShowMyForm();
            System.Console.WriteLine(
"Csharp main function end!");
        }

    }

}

3)CLI/C++的warpper,DLLexport函数CallCsharpForm(),此函数中调用C#的MyForm

CPPCLIPROXYDLLFORCSHARPDLL_API void CallCsharpForm();

#
using "../debug/CsharpDll.dll"

CPPCLIPROXYDLLFORCSHARPDLL_API 
void CallCsharpForm()
{
    CsharpDLL::MyForm
^ myForm = gcnew CsharpDLL::MyForm();
    myForm
->ShowMyForm();
}

4)NativeC++的exe调用CLI的Wrapper来间接的调用MyForm

#include "stdafx.h"
#include 
<iostream>
#pragma comment(lib, 
"../debug/CppCLIProxyDLLForCsharpDLL.lib")

void CallCsharpForm();

int _tmain(int argc, _TCHAR* argv[])
{
    std::cout
<<" Cpp Main function start:"<<std::endl;
    CallCsharpForm();
    std::cout
<<" Cpp Main function end!"<<std::endl;
    
return 0;
}

三 总结
要调试最好修改编译选项为Mixed。

代码下载: http://www.cppblog.com/Files/mzty/CppCallCsharpByCLI.rar

抱歉!评论已关闭.