1 软件版本信息
- Visual Studio 2015 Professional
- Matlab 2017b
- Operating System Windows 10
2 代码部分
2.1 Matlab代码
2.1.1 图片
2.1.2 源码
function [c] = gpuTestInCPlus(n)
clc;
fprintf('Creating a matrix of size %d-by-%d.\n',n, n);
A = rand(n,n,'single') + 100*eye(n,n,'single');
b = rand(n, 1);
gd = gpuDevice();
disp('Coefficient Matrix (A) is as follows: ');
A
disp('Right Hand Side Vector (b) is as follows: ');
b
disp('gpuArray Manner With Single Technique Involved: ')
tic;
Agpu=gpuArray(A);
bgpu=gpuArray(b);
c=A\b;
wait(gd);
toc;
end
2.2 C++代码
2.2.1 图片
2.2.2 源码
#include "stdafx.h"
#include "gpuTestInCPlus.h"
#include <iostream>
#include <windows.h>
using namespace std;
int main()
{
// Set up the application state for the MATLAB Runtime instance created in the application.
if (!mclInitializeApplication(NULL, 0)){
std::cerr << "could not initialize the application properly"
<< std::endl;
return -1;
}
// Load the required MATLAB code into the MATLAB Runtime.
if (!gpuTestInCPlusInitialize()){
std::cerr << "could not initialize the library properly"
<< std::endl;
return -1;
}
// Declare three variables using mxArray format
mwArray a(1, 1, mxDOUBLE_CLASS);
mwArray c(1, 3, mxDOUBLE_CLASS);
double x = 3;
double *sum = new double[3];
a.SetData(&x, 1);
// Invoke gpuTestInCPlus() method compiled in Matlab 2017b environment
gpuTestInCPlus(1, c, a);
// Retrieve results from matlab
c.GetData(sum, 3);
// Output results
cout << "State vector is: " << endl;
for (int j = 0; j<3; j++)
cout << sum[j] << " "<<endl;
cout << "it is successful !" << endl;
// Release all state and resources used by the MATLAB Runtime for the application
gpuTestInCPlusTerminate();
mclTerminateApplication();
getchar();
return 0;
}
3 Matlab代码编译成动态链接库(便于C++以动态链接库形式调用)
4 C++项目配置
4.1 C++基本配置
4.2 Matlab编译文件使用(编译文件只有lib、dll和.h文件有用,但是每个文件位置拷贝略有所区别!!!)
5 运行结果
6 参考链接
中途出现问题:程序找不到相应动态链接库文件、亦或内存异常等较多异常信息,但最关键的是调用Matlab时初始化总是提示内存异常,导致程序无法继续往前执行,查阅较多资料,唯一有效的解决办法就是改变编译设置,将自动编译模式改为仅限托管模式。
问题描述:内存异常大致状态如下所示,可定义为(Matlab C++ Shared Dll Library Initialization Problem),但是实际中内存异常时,相同程序不同电脑编译时内存异常数字略有所不同。
解决办法:
有用链接:
http://www.zyh1690.org/c-calling-matlab-generated-dynamic-link-library/
http://blog.csdn.net/yzl20092856/article/details/47065571
https://www.mathworks.com/matlabcentral/answers/373411-compiled-application-does-not-run-because-of-startup-plugin-libmwlmgrimpl-dll
http://www.ilovematlab.cn/thread-496143-1-1.html
http://dev.dafan.info/detail/453966?p=29-42
https://www.mathworks.com/matlabcentral/answers/286624-matlab-c-shared-dll-library-initialization-problem(备注:解决此问题的关键帖子)