C#以方便著称,特别是在界面上更是高效,但在效率上却与C相去甚远,为此要提高编程效率,可以用C#和C混合编程:用C#拖界面,用C写算法,下面是用VS2008调用VC++6.0编写的dll的一个例子
1.启动VC++6.0,建立一个动态连接库项目DllforCsharp。头文件是Dfc.h
#ifdef DFC_EXPORTS
#define DFC_API __declspec(dllexport)
#else
#define DFC_API __declspec(dllimport)
#endif
#include <windows.h>
extern "C" DFC_API int Max(int a,int b);
class Use{
public:
DFC_API void show(char* c);
};
源文件Dfc.cpp
#ifndef DFC_EXPORTS
#define DFC_EXPORTS
#endif
#include "Dfc.h"
#include <iostream>
using namespace std;
extern "C" DFC_API int Max(int a,int b){
return a+b;
}
DFC_API void Use:: show(char* c){cout<<c;}
BOOL APIENTRY DllMain( HANDLE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}
编译运行生成DllforCsharp.dll 和DllforCsharp.lib
2.新建一个.net windowsconsole 项目ConsoleApplication2,新建一个c#文件Program.cs
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
namespace ConsoleApplication2
{
public class Program
{
[DllImport("DllforCsharp.dll", EntryPoint = "Max", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
public static extern int Max (int a,int b);
[DllImport("DllforCsharp.dll", EntryPoint = "?show@Use@@QAEXPAD@Z", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall)]
public static extern void show(string c);
public static void Main() {
int value = Max(3,4);
Console.WriteLine(value);
string d = "aaa";
show(d);
Console.Read();
}
}
}
4将以上文件拷贝到ConsoleApplication2下的debug中,与可执行文件在同一目录。
解释:DllImport("DllforCsharp.dll", EntryPoint = "Max", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)
EntryPoint 为主函数入口,可用dumpbin查询。方法:cmd 进入DllforCsharp.dll所在的目录,输入以下命令
dumpbin /exports DllforCsharp.dll
5.c++ char* 到c#变成string CharSet = CharSet.Ansi,其他情况CharSet = CharSet.Auto即可。
6.运行以上程序即可。