在.net項目中需要調用Matlab生成的DLL,但是在調用過程中報錯,截圖如下:
在網上搜索一下資料,看到該博客:https://cn.mathworks.com/matlabcentral/newsreader/view_thread/282351
知道了我調用的DLL中有Matlab工具箱里面的函數,Matlab不允許某些工具箱中的工具被封裝成DLL,於是就出現了上圖所示的錯誤。
然后想用R語言實現。
1、先下載R軟件:http://mirrors.opencas.cn/cran/,選擇base
2、下載RDotNet並編譯
下載地址:http://rdotnet.codeplex.com/
下載好后 打開 RDotNet.Tests解決方案,進行編譯
編譯好的RDotner下載地址如下:http://pan.baidu.com/s/1c2NTnK8
3、測試
新建一個工程,引用如下圖:
代碼如下:
private static void Main(string[] args) { string rHome = null; string rPath = null; if (args.Length > 0) rPath = args[0]; if (args.Length > 1) rHome = args[1]; Console.WriteLine(RDotNet.NativeLibrary.NativeUtility.FindRPaths(ref rPath, ref rHome)); rHome = null; rPath = null; REngine.SetEnvironmentVariables(rPath: rPath, rHome: rHome); REngine e = REngine.GetInstance(); //Console.WriteLine(RDotNet.NativeLibrary.NativeUtility.SetEnvironmentVariablesLog); // .NET Framework array to R vector. NumericVector group1 = e.CreateNumericVector(new double[] { 30.02, 29.99, 30.11, 29.97, 30.01, 29.99 }); e.SetSymbol("group1", group1); // Direct parsing from R script. NumericVector group2 = e.Evaluate("group2 <- c(29.89, 29.93, 29.72, 29.98, 30.02, 29.98)").AsNumeric(); // Test difference of mean and get the P-value. GenericVector testResult = e.Evaluate("t.test(group1, group2)").AsList(); double p = testResult["p.value"].AsNumeric().ToArray()[0]; Console.WriteLine("Group1: [{0}]", string.Join(", ", group1)); Console.WriteLine("Group2: [{0}]", string.Join(", ", group2)); Console.WriteLine("P-value = {0:0.000}", string.Join(", ", p)); e.Dispose(); }
程序會根據R軟件的注冊表找到對應的dll從而實現調用R語言。
如果想指定R軟件的路徑可以將上面的代碼修改如下:
string rHome = @"E:\R-3.2.4revised"; string rPath = Path.Combine(rHome, @"bin\i386"); REngine.SetEnvironmentVariables(rPath,rHome);
在調用R語言的時候,如果有的程序包沒有引用的話需要在R程序菜單下的 “程序包” 來安裝對應功能的程序包。
解決問題參考的博客:
https://psychwire.wordpress.com/2011/06/19/making-guis-using-c-and-r-with-the-help-of-r-net/
http://blog.csdn.net/guoer9973/article/details/45953471
若程序運行失敗,提示
Fatal error: Unable to open the base package
和 找不到 R.DLL錯誤,
說明R軟件設置了環境變量,程序會優先使用環境變量,如果R的環境變量和你使用的R軟件路徑不一致就會出現上面的錯誤,這時候需要修改或者刪除R的環境變量,然后重啟一下電腦。
刪除方法:
打開注冊表:在“運行”里面輸入“regedit”
進入下面路徑,然后修改或刪除R_HOMR值,重啟一下電腦就可以了。
HKEY_LOCAL_MACHINE\SYSTEM\ControlSet003\Control\Session Manager\Environment