2010-05-27 34 views
1

我有一組代碼,根據程序的啓動方式,代碼將在本地執行或發送到遠程機器執行。理想的辦法我想這可能是工作看起來像下面這樣:例程來評估代碼或通過udp傳輸

line_of_code = 'do_something_or_other();'; 

if execute_remotely 
    send_via_udp(line_of_code); 
else 
    eval(line_of_code); 
end 

的事情是,我知道eval()功能是可笑的低效。另一方面,如果我在if區段的每個區段中寫出line_of_code,則會出現錯誤。除了簡單地使用eval()之外,還有其他方式可以更有效嗎?

+0

你知道UDP對它可以傳輸的消息有大小限制嗎?當你測試時,這往往表現爲工作正常,然後當你向老闆(老闆)演示一個演示時會出現災難性的錯誤。如果你遇到這種情況,你需要切換到TCP套接字,你沒有任何這樣的限制(作爲對需要更多設置的回報)。 – 2010-05-27 21:36:26

回答

3

編輯:經過更多的考慮和在評論中的一些討論,我有我懷疑函數句柄可以通過UDP傳輸。因此,我更新我的答案,而是建議使用功能FUNC2STR到功能手柄轉換爲字符串進行傳輸,然後使用功能STR2FUNC將其轉換回傳輸後再次函數句柄...

爲了解決使用EVAL,您可以使用function handle而不是存儲的代碼行中的字符串來執行:以上

fcnToEvaluate = @do_something_or_other; %# Get a handle to the function 

if execute_remotely 
    fcnString = func2str(fcnToEvaluate); %# Construct a function name string 
             %# from the function handle 
    send_via_udp(fcnString);    %# Pass the function name string 
else 
    fcnToEvaluate();      %# Evaluate the function 
end 

認爲函數do_something_or_other已經存在。然後,您可以做類似的遠程系統上執行以下操作:

fcnString = receive_via_udp();  %# Get the function name string 
fcnToEvaluate = str2func(fcnString); %# Construct a function handle from 
             %# the function name string 
fcnToEvaluate();      %# Evaluate the function 

只要該函數do_something_or_other代碼(即M-文件)存在於本地和遠程系統兩者,我覺得這應該工作。請注意,您也可以使用FEVAL來評估函數名稱字符串,而不是先將其轉換爲函數句柄。

如果您需要動態創建一個功能,可以初始化fcnToEvaluate在你的代碼的anonymous function

fcnToEvaluate = @() disp('Hello World!'); %# Create an anonymous function 

以及發送,接收代碼,並評價這應該是與上面相同。

如果你有參數傳遞給你的函數,你可以把函數句柄和輸入參數放到一個cell array。例如:

fcnToEvaluate = @(x,y) x+y; %# An anonymous function to add 2 values 
inArg1 = 2;     %# First input argument 
inArg2 = 5;     %# Second input argument 
cellArray = {fcnToEvaluate inArg1 inArg2}; %# Create a cell array 

if execute_remotely 
    cellArray{1} = func2str(cellArray{1}); %# Construct a function name string 
              %# from the function handle 
    send_via_udp(cellArray);    %# Pass the cell array 
else 
    cellArray{1}(cellArray{2:end}); %# Evaluate the function with the inputs 
end 

在這種情況下,用於send_via_udp可以代碼必須打破單元陣列並單獨發送每一個小區。收到時,函數名稱字符串將再次必須使用STR2FUNC轉換回函數句柄。

+0

函數參數怎麼樣?記住,它們是用字符串編碼的。 feval()接受函數,然後接受每個單獨的參數,而不是可以分析爲參數的字符串。我如何通過它們? – eykanal 2010-05-27 21:06:07

+0

@eykanal:我爲你如何處理輸入參數添加了一個例子。 – gnovice 2010-05-27 21:19:50

+0

@gnovice - 函數句柄是否實際傳遞函數的內容?我一直認爲函數句柄是對函數的引用,而不是函數本身。但我不希望一個參考在遠程機器上工作。我的理解是完全錯誤的嗎?這是一個很好的解決方案(如果有效的話))。 – mtrw 2010-05-27 21:53:24