C生成DLL供C#或VB调用

以Visual  Studio 2008为例。当然Visual Studio 2008一定要安装有C++和C#。

一。打开Visual Studio 2008,新增一工程,选择“其它语言工程”-Visual C++- Win32项目”

项目取名为COMDemo1

 

给项目添加两文件COMDemo1.cCOMDemo1.h

代码不做解释。

源码如下COMDemo1.c

#include #define _EXPORTDLL #include "COMDemo1.h" BOOL APIENTRY DllMain (HINSTANCE hInst /* Library instance handle. */ , DWORD reason /* Reason this function is being called. */ , LPVOID reserved /* Not used. */ ) { switch (reason) { case DLL_PROCESS_ATTACH: break; case DLL_PROCESS_DETACH: break; case DLL_THREAD_ATTACH: break; case DLL_THREAD_DETACH: break; } /* Returns TRUE on success, FALSE on failure */ return TRUE; } void CallFromDll(char* str) { str= "Welcome "; } int lmadd(int a,int b) { return a+b; } int lmsub(int a,int b) { return a-b; } int lmgetnum() { return 28; }

COMDemo1.h

#ifndef _DLLMAIN_H #define _DLLMAIN_H #ifdef _EXPORTDLL #define _LIBAPI __declspec(dllexport) #else #define _LIBAPI __declspec(dllimport) #endif /* Export following functions */ _LIBAPI void CallFromDll(char* str); _LIBAPI int lmadd(int a,int b); _LIBAPI int lmsub(int a,int b); _LIBAPI int lmgetnum(int a,int b); #endif

 

二。新建一C# Windwo窗体应用程序,打开程序自动生成的Form1窗口。引入新生成的DLL文件。示例代码如下。

 

using System; using System.Windows.Forms; using System.Runtime.InteropServices; namespace WindowsFormsApplication2 { public partial class Form1 : Form { [DllImport("COMDemo1.dll", EntryPoint = "lmsub")] public static extern int lmsub1(int a, int b); [DllImport("D://LIMINGTEST//COMDemo1//Release//COMDemo1.dll", EntryPoint = "lmadd")] public static extern int lmadd1(int a, int b); [DllImport("COMDemo1.dll", EntryPoint = "CallFromDll")] public static extern void CallFromDll1(ref string a); public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { int a = 0; a = lmadd1(3, 1); MessageBox.Show(a.ToString()); } private void button2_Click(object sender, EventArgs e) { string str = "liming"; CallFromDll1(ref str); MessageBox.Show(str); } } }

 

注意:如果没有把新生成的COMDemo1.DLL放入系统System文件夹,则要指定其绝对路径。

 

加入自己的代码编译调试即可。

 

 

 

 

你可能感兴趣的:(标准C)