簡體   English   中英

Matlab如何知道有.mex64文件並避免無限“編譯”循環

[英]How Matlab knows there is a .mex64 file and avoid infinity “compiling” loop

我創建了一個MyMex.m和一個MyMex.cpp。 在.m內部,我使用mex編譯.cpp。 僅當.mex64不存在時才會發生。 .mex64符合Matlab PATH中的目錄。 但是如果我沒有將Matlab當前工作目錄設置為.mex64目錄,那么Matlab將繼續在無限循環上運行.m。 我錯過了什么?

MyMex.m:

function [dataOut] = MyMex(dataIn)

mexCppFile = 'MyMex.cpp';
mexCmd = 'mex MyMex.cpp;';

fprintf('\nFile %s not compiled yet, compiling it now...\n%s\n',mexCppFile,mexCmd);
fileFullPath = which(mexCppFile);

if size(fileFullPath,2) > 0 && exist(fileFullPath,'file')
    [fileDir, fileName, ext] = fileparts(fileFullPath);
    curDir = pwd;
    cd(fileDir);
    mex MyMex.cpp;
    cd(curDir);
else
    error('prog:input','Unable to find %s to compile it. Check if the file is in the current dir or in the Matlab PATH!',mexCppFile);
end

% Call C++ mex
[dataOut] = MyMex(dataIn)
end

編輯以保護自己免受我做無限循環的評論:Matlab應該知道該函數的編譯版本。 我不知道它是如何做到的,我的問題與此有關,因為有時它發現函數有時卻沒有。

這是一個統一的在線mex示例,它可以執行相同的“無限”操作並順利運行:

2D插值

他的代碼在mirt2D_mexinterp.m中:

% The function below compiles the mirt2D_mexinterp.cpp file if you haven't done it yet.
% It will be executed only once at the very first run.
function Output_images = mirt2D_mexinterp(Input_images, XI,YI)

pathtofile=which('mirt2D_mexinterp.cpp');
pathstr = fileparts(pathtofile);
mex(pathtofile,'-outdir',pathstr);

Output_images = mirt2D_mexinterp(Input_images, XI,YI);

end

也許.m和.mex64需要在同一個文件夾中。

這一切都歸結為Matlab的搜索路徑 如果Mex文件位於路徑中的同一級別,則它們優先於m文件。 並且當前目錄中的文件優先於在matlab搜索路徑中的其他位置找到的文件。 因此,當您遇到無限循環時,很明顯m文件在搜索路徑中位於比mex文件更高的位置。

實質上,如果兩個文件位於同一文件夾中,則一切正常。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM