C++和C#混合編程
最近需要利用C++和C#混合編程,然后就寫了一個C#調用C++生成的DLL的DEMO。困擾我好久的就是C#中string類型在C++里面怎么表達,現在把C++生成DLL供C#調用的流程寫出來。
源碼:百度網盤
1、打開VS創建C++項目"C++_CScharp_DLL"

點擊確定之后接着點擊下一步:

然后選擇應用程序和附加選項:

點擊完成,C++的項目就新建好了。
2、添加代碼文件
右鍵項目,添加類,如下圖所示:

添加類之后會打開添加文件對話框,點擊添加即可,如下圖所示:

點擊確定之后進去下一個對話框,填寫文件名Function,如下圖所示:

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

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++項目里面設置,讓動態庫受到公共語言運行時的支持。如下圖所示:
打開項目屬性


修改完成后點擊項目右鍵生成DLL,看是否報錯,成功結果如下圖:

3、添加測試程序:
在該解決方案中添加測試程序:

添加一個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(1, 2));
Console.WriteLine(fun.say("Hello World"));
Console.ReadKey();
}
}
}
現在就可以點擊調試按鈕調試了,調試結果如圖所示:


