(如需交流,请关注公众号:神马观止)
由于之前一直使用MFC,所以对于C#并没有太多的学习,然而MFC编写界面的繁琐让大量的时间耗费在了GUI的排版和构建中。所以,最终我选择了用C# Windows Form。然而,为了将核心算法模块和GUI剥离开,最终我选择了以C# Windows Form构建GUI,C++ DLL实现核心算法的编程框架,并坚持以后都以此框架来编写常用算法分析和仿真工具。我以VS2008为例:
1. 首先新建Win32 Console Apllication工程,记得更改Solution Name。
然后,选择Apllication type,而Additional options可勾选Export symbols,如下图所示:
2.构建TestDll工程
默认生成了3个.h文件和3个.cpp文件。现在需要添加三个文件,即:
(1) TestDataStructure.h----专门用来定义所需要的数据类型,方便后面使用
(2) ExportAPI.cpp----作为需要导出API的接口函数
(3) DefAPI.def----这个文件非常重要,定义了函数的导出点,这样在C#程序中才能调用这个函数
如图:
具体文件内容如下:
(1) TestDll.h
// The following ifdef block is the standard way of creating macros which make exporting
// from a DLL simpler. All files within this DLL are compiled with the TESTDLL_EXPORTS
// symbol defined on the command line. this symbol should not be defined on any project
// that uses this DLL. This way any other project whose source files include this file see
// TESTDLL_API functions as being imported from a DLL, whereas this DLL sees symbols
// defined with this macro as being exported.
#ifndef __TESTDLL_H__
#define __TESTDLL_H__
#define TESTDLL_API __declspec(dllexport)
#endif
(2) TestDll.cpp
// TestDll.cpp : Defines the exported functions for the DLL application.
//
#include "stdafx.h"
#include
#include "TestDll.h"
#include "TestDataStructure.h"
using namespace std;
CTestDll::CTestDll()
{
width = 6.0;
height = 4.0;
flag = 1;
}
float CTestDll::CalculateArea(float w, float h)
{
if ((w > 0 && h > 0) && (1 == flag))
return w * h;
else
{
cout << "Something wrong!" << endl;
return -1;
}
}
bool CTestDll::IsTriangle()
{
if (1 == flag)
return true;
else
return false;
}
(3) TestDataStructure.h
#ifndef __TESTDLL_TEST_DATA_STRUCTURE__
#define __TESTDLL_TEST_DATA_STRUCTURE__
#include "TestDll.h"
// This class is exported from the TestDll.dll
class TESTDLL_API CTestDll {
public:
CTestDll(void);
// TODO: add your methods here.
float CalculateArea(float, float);
bool IsTriangle();
public:
float width;
float height;
bool flag;
};
#endif
(4) ExportAPI.cpp
#include "stdafx.h"
#include "TestDll.h"
#include "TestDataStructure.h"
// This is an example of an exported function.
TESTDLL_API float fnTestDll(void)
{
CTestDll testdll;
float w = testdll.width;
float h = testdll.height;
float area = testdll.CalculateArea(w, h);
return area;
}
(5) DefAPI.def
LIBRARY "TestDll"
EXPORTS
fnTestDll;
3. 构建C#主程序
这里为了简单起见采用C# Console Application,在Solution中选择“Add to Solution”,如图:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
namespace TestGUI
{
class Program
{
[DllImport("../../../Debug/TestDll.dll")]
public static extern float fnTestDll();
static void Main(string[] args)
{
Console.WriteLine("******************* Main Start **********************");
Console.WriteLine(fnTestDll());
Console.Read();
}
}
}