C#学习笔记(二)——C语言DLL

一、DLL生成(需要.h和.c两个文件)

add.h内容:


#ifndef _DLL_H_
#define _DLL_H_

#if BUILDING_DLL
#define DLLIMPORT __declspec(dllexport)
#else
#define DLLIMPORT __declspec(dllimport)
#endif

DLLIMPORT int Add();    声明函数

#endif

========================================================================================
add.c内容

#include "dll.h"                                   //引入头文件
#include <windows.h>

DLLIMPORT int Add(int a,int b)             //定义需要实现功能的函数
{
	return a+b;
}

BOOL WINAPI DllMain(HINSTANCE hinstDLL,DWORD fdwReason,LPVOID lpvReserved)                                    //DLL主函数入口,暂时默认不动
{
	switch(fdwReason)
	{
		case DLL_PROCESS_ATTACH:
		{
			break;
		}
		case DLL_PROCESS_DETACH:
		{
			break;
		}
		case DLL_THREAD_ATTACH:
		{
			break;
		}
		case DLL_THREAD_DETACH:
		{
			break;
		}
	}
	
	/* Return TRUE on success, FALSE on failure */
	return TRUE;
}
================================================================================================
DELL引用(C#)

1.将DLL文件放入DEBUG文件夹
2.Program.cs中

(1) using System.Runtime.InteropServices;   //加载DLL申明

(2)class dll                                                //专门用一个CLASS来处理DLL程序
    {
        [DllImport("Add.dll")]                           //载入DLL
        public static extern int Add(int a,int b);  //声明函数原型
    }
(3)具体窗体事件中运行函数

        private void button1_Click(object sender, EventArgs e)
        {
            int sun = dll.Add(8, 7);                                //引用函数要在函数名前加  CLASS. 否则无法实现
            textBox1.Text = "测试成功,计算结果为:"; 
            textBox1.AppendText(sun.ToString());                    //sun.ToString()将变量sun转换成String格式;AppendText向文本框追加显示内容
        }

读取数据、运算数据、显示数据实例:
 private void button1_Click(object sender, EventArgs e)
        {

            int x, y, sun;
            x = Convert.ToInt32(textBox3.Text);      //读取TEXTBOX中的数字
            y = Convert.ToInt32(textBox2.Text);
            sun = ccc.add(x,y);                      /*引用函数要在函数名前加  CLASS. 否则无法实现*/
            textBox1.Text = "测试成功,计算结果为:";  //显示文本(字符串)
            textBox1.AppendText(sun.ToString());     //将数字转换为字符串显示    
			
        }

  

猜你喜欢

转载自www.cnblogs.com/gougouwang/p/11669561.html