編輯:經過更多的考慮和在評論中的一些討論,我有我懷疑函數句柄可以通過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轉換回函數句柄。
你知道UDP對它可以傳輸的消息有大小限制嗎?當你測試時,這往往表現爲工作正常,然後當你向老闆(老闆)演示一個演示時會出現災難性的錯誤。如果你遇到這種情況,你需要切換到TCP套接字,你沒有任何這樣的限制(作爲對需要更多設置的回報)。 – 2010-05-27 21:36:26