看了第一篇感覺沒啥用對吧,來點稍微有用的。
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路徑:.\bin\x86\debug。
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();
}
}
}