C++/CLI入门系列 第二篇:封装C++ dll库,提供接口给C#调用

看了第一篇感觉没啥用对吧,来点稍微有用的。
1、先建个c#工程,依次 file -> new -> project,选择 visula c# -> console application,写工程名,点 ok。

2、再建个c++ dll工程。依次 file -> add -> new project。选择 visual -> win32 console application,点 ok -> next,选择 dll -> finish。

 


3、建立cli工程。依次 file -> add -> new project。选择 visula c++ -> clr -> class library,写工程名,点 ok。

4、创建结束,开始配种,啊呸!配置。
1)、c#工程默认平台any cpu,强迫症犯了,改成x86,编译下,生成目标debug路径:.inx86debug。
2)、修改c++工程输出目录、cli工程输出目录、cli工程库引入路径等为上方目录。
3)、修改cli引入头文件路径为包含CppDll.h的路径。
4)、依次编译c++工程,cli工程
5)、c#工程导入CliDll,依次选择 c#工程 -> references -> 点右键 -> add reference -> browse -> 选择debug路径下由cli工程生成的dll文件。
6)、编译c#工程,最后运行。

附源码:
github仓库项目地址:git@github.com:fx-odyssey/CS_Cli_Cpp.git(vs2008工程,打开可直接运行)

//CppDll.h

#pragma once

#include <stdio.h>

#include <stdlib.h>

#ifdef CPPDLL_EXPORTS

#define CPP_EXPORTS __declspec(dllexport)

#else

#define CPP_EXPORTS __declspec(dllimport)

#endif

extern "C" CPP_EXPORTS int Add(int a, int b);

extern "C" CPP_EXPORTS int Sub(int a, int b);

extern "C" CPP_EXPORTS int Mul(int a, int b);

extern "C" CPP_EXPORTS int Div(int a, int b);

***************************************

// CppDll.cpp

#include "stdafx.h"

#include "CppDll.h"

int Add(int a, int b)

{

return a + b;

}

int Sub(int a, int b)

{

return a - b;

}

int Mul(int a, int b)

{

return a * b;

}

int Div(int a, int b)

{

return a / b;

}

**************************************

// CliDll.h

#pragma once

#include <iostream>

#include "CppDll.h"

using namespace System;

using namespace System::Runtime::InteropServices;

using namespace System::Collections::Generic;

using namespace System::Collections;

using namespace std;

#pragma comment(lib, "CppDll.lib")

#pragma managed

namespace CliDll {

public ref class Arith

{

public:

Arith();

~Arith();

int AddCli(int a, int b);

int SubCli(int a, int b);

int MulCli(int a, int b);

int DivCli(int a, int b);

};

}

**************************************

// CliDll.cpp

#include "stdafx.h"

#include "CliDll.h"

using namespace CliDll;

CliDll::Arith::Arith(){}

CliDll::Arith::~Arith(){}

int CliDll::Arith::AddCli(int a, int b)

{

return Add(a, b);

}

int CliDll::Arith::SubCli(int a, int b)

{

return Sub(a, b);

}

int CliDll::Arith::MulCli(int a, int b)

{

return Mul(a, b);

}

int CliDll::Arith::DivCli(int a, int b)

{

return Div(a, b);

}

*************************************

//Program.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using CliDll;

namespace CSProject

{

class Program

{

static void Main(string[] args)

{

Arith arith = new Arith();

int back1 = arith.AddCli(1, 2);

Console.WriteLine(back1.ToString());

int back2 = arith.SubCli(3, 4);

Console.WriteLine(back2.ToString());

int back3 = arith.MulCli(4, 5);

Console.WriteLine(back3.ToString());

int back4 = arith.DivCli(8, 4);

Console.WriteLine(back4.ToString());

Console.ReadLine();

}

}

}

原文地址:https://www.cnblogs.com/lvdongjie/p/13962856.html