首先,这种调用在 Matlab 的帮助文档中有说明。它的英文名称为:
MATLAB Interface to Generic
DLLs
从这个帮助文档,我们不难看出,整个过程为:加载
DLL ,调用相关函数,和卸载 DLL 。
看起来简单,但是在实际操作中遇到了如下几个问题:
1,
loadlibrary 出错。错误报告为:
Error using ==>
loadlibrary Failed to preprocess input file. Output from
preprocessor is: 'c:program' is not recognized as an internal or
external command, operable or batch file
错误的原因很简单,就是 loadlibrary 的问题。由于你的 matlab 是安装在 C:program
file 目录下,中间有一个空格。所以出错了。这在
Matlab R14sp2
及其以前的版本都有这个问题。
解决办法:
-
重新安装 matlab ,换一个目录,中间不带空格。
modify
line 168 of loadlibrary.m in
toolboxmatlabgeneral from:
cc=[lcc ' -noregistrylookup'
ccinclude ' -E "' header '"'];
to:
cc=['"' lcc '"
-noregistrylookup' ccinclude ' -E "' header '"']; If your header
has #include statements, then it might also be necessary to modify
the following lines:
line 106 from:
ccinclude = [ccinclude ' -I '
fullfile(matlabroot, 'extern','include')];
to:
ccinclude = [ccinclude ' -I "'
fullfile(matlabroot,'extern','¬include"')];
line 166 from:
ccinclude = [ccinclude ' -I '
fullfile(matlabroot,'sys',...
'lcc','include')];
to:
ccinclude = [ccinclude ' -I "'
fullfile(matlabroot,'sys',...
'lcc','include"')];
The line numbers might be
different in previous releases, but the changes are the
same
注意:千万注意其中的空格。否则, matlab 告诉出错,可不要挠头。
2,
loadlibrary 成功了。但是查询 libfunctions 或卸载 unloadlibrary 不成功。
怪了。我仔细看了看 loadlibrary 中的头文件。由于我写 DLL 的时候提供的头文件是给 VC 用的,所以其中有些是 VC 环境中自定义的东西。我把这个头文件改了改,把
DLL 相关的部分给注释掉,如:
#ifdef
DATATRANSFER_API
//#define DATATRANSFER_API
extern "C" __declspec(dllexport)
#else
#define DATATRANSFER_API extern
"C" __declspec(dllimport)
#endif
//DATATRANSFER_API
int
GYZPrepare(void);
如上面,把这个 DLL 相关的注释掉,就剩下一个简单的 .h 文件。呵呵,这样就通过了。
3,
参数传递。
由于我的程序很简单,所以就不管这些啦。