C#与C++混合编程(入门级)
目的
一直在从事图像算法工作,但光懂算法觉得挺被动,于是想在软件方面突破一下,C#在做界面的时候很方便,所以先得搞清楚C#是如何与C++交互的,废话不多说,开始手把手创建一个C#调用C++的项目。
步骤
- 创建C++dll工程
- 创建C#工程
- 引用C++的dll
- 执行C#主函数
详细过程
1.打开VS,创建C++项目C++_DLL
2.下一步,选择DLL,空项目,完成
3.解决方案平台,默认×86,我习惯用×64,所以我改成下面的
4.给类起个名字DllFunction
5.编写一个加法,一个打印语句
此时会提示语法错误,别急,在属性-常规-公共语言支持,选择“公共语言运行时支持clr”
DllFunction.h
#pragma once
#include <string>
public ref class DllFunction
{
public:
DllFunction();
~DllFunction();
int Add(int x, int y);
System::String^ SayHi(System::String^ str);
};
DllFunction.cpp
#include "DllFunction.h"
DllFunction::DllFunction()
{
}
DllFunction::~DllFunction()
{
}
int DllFunction::Add(int x, int y)
{
return x + y;
}
System::String^ DllFunction::SayHi(System::String^ str)//C#中指针用^表示
{
return str;
}
6.点击右键生成dll
7.新建C#项目
8.控制台应用程序,Test
9.添加引用
10.勾选C++生成的DLL
11.添加测试代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Test
{
class Program
{
static void Main(string[] args)
{
DllFunction fun = new DllFunction();
int sum = fun.Add(1, 2);
Console.WriteLine(sum);
string ss = fun.SayHi("你好,码农");
Console.WriteLine(ss);
Console.ReadKey();
}
}
}
12.将C#项目设为启动项
13.点击启动
这时会报一个异常,是×64引起的,此时需要在属性-生成-目标平台,选择×64,再次启动
得到运行结果:
感谢阅读,欢迎提各种意见!