dll创建和使用

简介:

 通过C++项目创建dll,C#项目使用dll。

代码下载链接。

 

 1.创建

  1. 创建Winform项目,用于测试使用dll。
  2. 创建“Win32项目”,用于创建dll。在解决方案右键->添加,这样可以两个项目会在同一解决方案下。
  3. 创建对应cpp和h文件。

 

同一个解决方案新建项目

 

Win32项目

 

选择DLL

 

向导结束

 

2.代码

  • .cpp文件
  1. 函数名前加上 My_API,表明函数被导出。
#include "stdafx.h"
#include "mydll.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#endif

bool My_API Init()
{
	AfxMessageBox(_T("Init"));
	return true;
}
  • .h文件 
  1. 定义My_API _declspec(dllexport) _stdcall。
  2. 定义__cplusplus extern "C"相关。
  3. 声明函数。

#ifndef _mydll_H_
#define _mydll_H_

#pragma once

#ifdef __cplusplus
extern "C" {
#endif

#define My_Dll

#ifdef My_Dll
#define My_API _declspec(dllexport) _stdcall
#else
#define My_API _declspec(dllimport) _stdcall
#endif

bool My_API Init();

#ifdef __cplusplus
}
#endif
#endif // !_mydll_H_

 

  • 使用dll
  1. 新建个类,可以单独放在一个文件下。
  2. [DllImport("dll创建.dll", EntryPoint = "Init")]。通过这种方式使用dll内的函数。如果函数含有相应的变量类型,需要对应的转换。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace dll引用
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btnInit_Click(object sender, EventArgs e)
        {
            MyDll.Init();
        }
    }

    public class MyDll
    {
        [DllImport("dll创建.dll", EntryPoint = "Init")]
         public static extern bool Init();
    }

}

 

3.报错

  1. stdafx.h默认会包含windows.h。AfxMessageBox需要afxwin.h,需要把其放在windows.h前面,否则编译报错。内容如下:错误    2    error C1189: #error :  WINDOWS.H already included.  MFC apps must not #include <windows.h>  。
  2. dll未放在exe目录下,调用dll内的函数时会出错。内容如下:找不到指定的模块。
  3. 如果头文件未使用__cplusplus extern "C"相关,调用函数时会出错。内容如下:Unable to find an entry point named 'Init' in DLL。
  4. 借助Dependency Walker查看dll。
  5. 生成的dll等输出文件,设置路径到exe目录下,方便调试。
  6. 如果有使用MFC的类,需要设置属性“在共享DLL中使用MFC”或“在静态库中使用MFC”。
  7. 在使用dll的项目中,通过属性->调试->启用本机代码调试。方可在生成dll项目中使用断点调试代码。

 

windows.h重复包含

 

找不到dll

 

找不到dll内的函数

 

查看dll

 

属性

 

启用本机代码调试

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值