简介:
通过C++项目创建dll,C#项目使用dll。
1.创建
- 创建Winform项目,用于测试使用dll。
- 创建“Win32项目”,用于创建dll。在解决方案右键->添加,这样可以两个项目会在同一解决方案下。
- 创建对应cpp和h文件。
2.代码
- .cpp文件
- 函数名前加上 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文件
- 定义My_API _declspec(dllexport) _stdcall。
- 定义__cplusplus extern "C"相关。
- 声明函数。
#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
- 新建个类,可以单独放在一个文件下。
- [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.报错
- stdafx.h默认会包含windows.h。AfxMessageBox需要afxwin.h,需要把其放在windows.h前面,否则编译报错。内容如下:错误 2 error C1189: #error : WINDOWS.H already included. MFC apps must not #include <windows.h> 。
- dll未放在exe目录下,调用dll内的函数时会出错。内容如下:找不到指定的模块。
- 如果头文件未使用__cplusplus extern "C"相关,调用函数时会出错。内容如下:Unable to find an entry point named 'Init' in DLL。
- 借助Dependency Walker查看dll。
- 生成的dll等输出文件,设置路径到exe目录下,方便调试。
- 如果有使用MFC的类,需要设置属性“在共享DLL中使用MFC”或“在静态库中使用MFC”。
- 在使用dll的项目中,通过属性->调试->启用本机代码调试。方可在生成dll项目中使用断点调试代码。