提高编程效率方法之一:初探C#和C混合编程

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.运行以上程序即可。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值