matlab与dll链接总结与整理
参考文献
问题1:编译正确选项为x64
而不是x86
。
dllAndMatlab_test
错误使用 loadlibrary
加载库 "D:\my-code\dllAndmatlabTest\dll_test.dll" 时出错
D:\my-code\dllAndmatlabTest\dll_test.dll ������Ч�� Win32 Ӧ�ó���
问题2:未添加正确的宏定义选项
问题描述如下
错误使用 loadlibrary
生成 add_dll_thunk_pcwin64 失败。编译器输出为:
cl -I"D:\matlabR2021a\extern\include" /Zp8 /W3 /nologo -I"D:\my-code\dllAndmatlabTest" -I"D:\my-code\dllAndmatlabTest" "add_dll_thunk_pcwin64.c" -LD
-Fe"add_dll_thunk_pcwin64.dll"
add_dll_thunk_pcwin64.c
D:\my-code\dllAndmatlabTest\add_dll.h(1): error C2059: 语法错误:“字符串”
实际上的头文件应该为:
#ifdef __cplusplus
extern "C"
{
#endif
int __declspec(dllexport) add_dll(int a, int b);
#ifdef __cplusplus
}
#endif
注意:其中为两个下划线。
附录代码
main.h
#ifdef __cplusplus
extern "C"
{
#endif
int __declspec(dllexport) add_dll(int a, int b);
#ifdef __cplusplus
}
#endif
#ifdef __cplusplus
extern "C"
{
#endif
int __declspec(dllexport) sub_dll(int a, int b);
#ifdef __cplusplus
}
#endif
main.c
#include"main.h"
int add_dll(int a, int b)
{
return a + b;
}
int sub_dll(int a, int b)
{
return a - b;
}
dllAndMatlab_test.m
function dllAndMatlab_test
%mex -setup c++
loadlibrary('dll_test.dll','main.h')
libfunctions('dll_test')
N=10;M=10;
error = zeros(N*M,1);
for i=1:N
for j=1:M
c = calllib('dll_test','add_dll',i,j);
error((i-1)*M+j) = c-(i+j);
end
end
plot(error)
unloadlibrary dll_test