C++和C#混合编程

时间:2023-03-09 08:56:24
C++和C#混合编程

最近需要利用C++和C#混合编程,然后就写了一个C#调用C++生成的DLL的DEMO。困扰我好久的就是C#中string类型在C++里面怎么表达,现在把C++生成DLL供C#调用的流程写出来。

源码:百度网盘

环境:win7+vs2010。

1、打开VS创建C++项目"C++_CScharp_DLL"

C++和C#混合编程

点击确定之后接着点击下一步:

C++和C#混合编程

然后选择应用程序和附加选项:

C++和C#混合编程

点击完成,C++的项目就新建好了。

2、添加代码文件

右键项目,添加类,如下图所示:

C++和C#混合编程

添加类之后会打开添加文件对话框,点击添加即可,如下图所示:

C++和C#混合编程

点击确定之后进去下一个对话框,填写文件名Function,如下图所示:

C++和C#混合编程

添加好后会生成h文件和cpp文件,如下图所示:

C++和C#混合编程

Function.h文件代码如下:

#pragma once
#include <string>
public ref class Function
{
public:
Function(void);
~Function(void);
int menber;
int menberFuncAdd(int a,int b);
System::String^ say(System::String^ str);
};

Function.cpp文件代码如下:

#include "Function.h"

Function::Function(void)
{
} Function::~Function(void)
{
} int Function::menberFuncAdd(int a,int b)
{
return a+b;
}
System::String^ Function::say(System::String^ str)
{
return str;
}

填写完后Function.h文件会报错,错误类型如下:

C++和C#混合编程

这里需要在C++项目里面设置,让动态库受到公共语言运行时的支持。如下图所示:

打开项目属性

C++和C#混合编程

C++和C#混合编程

修改完成后点击项目右键生成DLL,看是否报错,成功结果如下图:

C++和C#混合编程

3、添加测试程序:

在该解决方案中添加测试程序:

C++和C#混合编程

添加一个C#控制台测试程序:

C++和C#混合编程

添加完后设为启动项:

C++和C#混合编程

添加引用:

C++和C#混合编程

将C++项目添加到C#的项目中:

C++和C#混合编程

4、编写测试代码

Program.cs文件代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text; namespace Test
{
class Program
{
static void Main(string[] args)
{
Function fun = new Function();
Console.WriteLine(fun.menberFuncAdd(, ));
Console.WriteLine(fun.say("Hello World"));
Console.ReadKey();
}
}
}

现在就可以点击调试按钮调试了,调试结果如图所示:

C++和C#混合编程

异常情况:

运行的时候若出现未处理的异常导致dll加载失败,需要修改项目到对应的平台

C++和C#混合编程

修改方法如下:

C++和C#混合编程

源码:百度网盘