使用Win32汇编开发一个dll并在C#中调用

164 篇文章 18 订阅

使用RadASM,新建一个Dll Project;

下一步,默认;

dll包含Def文件;

完成工程构建;都默认;

完成以后项目结构如下;

asm代码;

.386
.model flat, stdcall
option casemap :none     
            
include         windows.inc 

.data?
    dwCounter       dd      ?

.code

DllEntry        proc    _hInstance,_dwReason,_dwReserved ;动态链接库的入口函数
                mov     eax,TRUE
                ret
DllEntry        Endp


_CheckCounter   proc ;功能函数1,确保数字的大小在0--10之间
       mov     eax,dwCounter
       cmp     eax,0
       jge     @F ;大于等于则跳转
       xor     eax,eax
       @@:
       cmp     eax,10
       jle     @F                                       
       mov     eax,10
       @@:
       mov     dwCounter,eax
      
       ret
_CheckCounter endp

_IncCounter     proc ;功能函数2,实现将当前的数字加1
       inc     dwCounter
       call    _CheckCounter
       ret
_IncCounter endp

_DecCounter     proc ;功能函数3,将当前的数字减1
       dec     dwCounter
       call    _CheckCounter
       ret
_DecCounter endp

_Mod            proc    uses ecx edx _dwNumber1,_dwNumber2 ;功能函数4,求输入的两个数的模
                xor     edx,edx
                mov     eax,_dwNumber1
                mov     ecx,_dwNumber2
                .if     ecx
                div    ecx
                mov    eax,edx
                .endif
       ret
_Mod endp
                End     DllEntry ;最后DLL的结尾

def文件;dll导出3个函数供外部调用,_Mod这个是求2个数的模;

在编程语言中,% 是取模运算符,或求余运算放,指的是求数除法的余数;比如,8%3 运算的值是2,计算的是第一个操作数除以第二个操作数的余数;

EXPORTS    _IncCounter
           _DecCounter
           _Mod

 从菜单编译,连接,构建;构建成功;

看下dll文件,lib文件这些出来了;

用C#做一个程序,尝试按调用C++ dll的方法进行调用;结果如下,可以调用;

 

C#代码如下;使用SharpDevelop工具;

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using System.Runtime.InteropServices;

namespace dlldemo1
{
	/// <summary>
	/// Description of MainForm.
	/// </summary>
	public partial class MainForm : Form
	{
		
        [DllImport("asmdlldemo.dll")]
        static extern int _Mod(int n1, int n2);

		public MainForm()
		{
			//
			// The InitializeComponent() call is required for Windows Forms designer support.
			//
			InitializeComponent();
			
			//
			// TODO: Add constructor code after the InitializeComponent() call.
			//
		}
		void Button1Click(object sender, EventArgs e)
		{
			int ret=_Mod(Int32.Parse(textBox1.Text), Int32.Parse(textBox2.Text));
			textBox3.Text=ret.ToString();
		}
	}
}

dll放到exe目录;如下;

 

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值