- 积分
- 65
- 注册时间
- 2004-2-22
- 仿真币
-
- 最后登录
- 1970-1-1
|
发表于 2004-5-12 08:52:20
|
显示全部楼层
来自 江苏南京大学
回复: 【讨论】关于CIN接口的一个小问题
1。// 新建一个空的Win32 Dll 工程
加入新的cpp,写入下面代码
_declspec(dllexport) int sum(int a, int b)
{
return a+b;
}
Build出一个dll:sum.dll
2。// 新建一个新的Win32 Console程序
选择Simple Console Application,修改main函数所在的cpp:
#include "stdafx.h"
// for IO
#include <iostream>
using namespace std;
// for base type and LoadLibrary
#include <WINDOWS.H>
// define function pointer which will point to sum(a, b)
typedef int(*Func)(int,int);
int main(int argc, char* argv[])
{
HMODULE dll = :oadLibrary("sum.dll");// 加载刚才那个dll,路经要对
if(dll)
{
Func f = (Func)GetProcAddress(dll, "?sum@@YAHHH@Z");// 加载那个sum函数
if(f)
cout<<f(3, 4); // 等价于调用 sum(3, 4)
else
cout<<"function call error";
}
else
cout<<"lodad error";
}
Build & Execute
3。上面一个不便的地方就是GetProcAddress,第二个参数是个很复杂的字符串,需要事先用dumpbin sum.dll /exports得到sum函数的实际名称
所以,一般会在最上面写dll时,导出函数前面不仅加上已有的红字表示导出,还要加上extern "C" ,表示以C方式编译,因为C方式编译时,函数名在库中和在程序代码中会保持一致,不像C++生成新的编码后的函数名。
那么,上述的dll函数声明就是
extern "C" _declspec(dllexport) int sum(int a, int b)
而调用程序的GetProcAddress行就改为:
Func f = (Func)GetProcAddress(dll, "sum");
4.编译为dll
5。在lv中用call library调用 |
评分
-
1
查看全部评分
-
|