1, 新建控制台工程 xdltest, 改属性 - 配置属性 - 常规 - 配置类型为 动态库. dll 或静态库. lib
2, 打开工程后添加 dltest.h, dltest.cpp, 其中. h 与. cpp 名字没必要一样
3, 编写代码
- ----------------------------------------------
- --dltest.h
- #pragma once
- _declspec(dllexport) void Print(const char* str);
- ----------------------------------------------
- --dltest.cpp
- #include<iostream>
- #include"dltest.h"
- void Print(const char* str)
- {
- std::cout <<"dltest>>" <<str << std::endl;
- }
4, 编译, 生成 <库的名字是根据工程名生成的>
若是静态库, 则会生成 xdltest.lib.
若是动态链接库则生成 xdltest.lib 和 xdltest.dll
5, 使用
(1)将 xdltest.lib 添加到 <属性 - 配置属性 - 链接器 - 输入 - 附加依赖项>
(2)在 <属性 - 配置属性 - 链接器 - 常规 - 附加库目录> 中指定 xdltest.lib 的目录
(3)在 <属性 - 配置属性 - c/c++- 常规 - 附加包含目录> 中指定 dltest.h 的目录
(4)在程序中 #include "dltest.h" 后即可使用 Print("hello")输出了
下面有三种方式使用库函数
-----------------------------------------
-- 使用方式一
- #include "stdafx.h"
- #include "abc.h" // 包含库的头文件
- int main()
- {
- Print("hello,world");
- return 0;
- }
- -----------------------------------------
-- 使用方式二
- #include "stdafx.h"
- void Print(const char* str); // 声明库中的函数, 使编译通过
- int main()
- {
- Print("hello,world");
- return 0;
- }
- -----------------------------------------
-- 使用方式三
- #include "stdafx.h"
- _declspec(dllimport) void Print(const char* str); // 从库中导入进工程
- int main()
- {
- Print("hello,world");
- return 0;
- }
6, 运行
若是动态链接库则必须把 dll 文件拷到 exe 目录下才能运行
原理:
.h 文件用于编译, 使程序在语法上检测通过, 利用这个原理,
可以不使用. h 文件而直接将需要使用的库函数在使用前声明出来
.lib 文件用于链接, 若是静态链接库, 直接将函数实现写入了 exe 中,
若是动态链接则是在 exe 中留下函数签名并标记它是运行时动态加载的
------------------------------------------------------------------------------------------------------
需要注意的是:
1,C# 只能调用 C/C++ 的 DLL, 而不能调用 lib,
2,C++ 生成的 DLL 中, 函数名被改了(各编译器而不同), 而 C# 调用 C++ DLL 时需要指定函数名字, 因此会出错, 找不到函数
对应方法是: 生成 C 风格的 DLL, 它的函数是没改名字的.
C 风格的 DLL 中函数声明加上 exterun "C", 如:
exterun "C" _declspec(dllexport) void Print(const char* str);
来源: http://www.bubuko.com/infodetail-2702796.html