登录论坛

查看完整版本 : [转帖]解决在c#.net下调用matlab函数时多出参数的一个参考


corriander
2008-03-17, 10:11
来源:

http://bingfeng.blog.edu.cn/user1/9009/archives/2007/1669318.shtml

解决在c#.net下调用matlab函数时多出参数的一个参考

是一个不认识的朋友让我帮他发在这儿,因为他遇到这个问题,在网上没有搜到答案,希望"我为人人,人人为我"更多


解决在c#.net下调用matlab函数时多出参数的一个参考。
和这个问题很类似:
[求助]C#中调用MATLAB生成的DLL问题请教
各位大侠,我想请教一个问题。在用MATLAB生成Dll被C#调用以后,在使用的过程中,本来的MATLAB中的函数 参数只有一个,但是怎么在调用以后就又三个参数呢,我MATLAB的函数是:function a=absole(b)
if b<0
a=-b;
else
a=b;
end
在C#中变成absole(int nargout,ref object a,object b)
这里的三个参数是什么意思呢?
还有就是这里的函数变成void absole(int nargout,ref object a,object b),为什么是无值返回呢啊!
请高手指点,急!!!

原文在 http://www.chinaaspx.com/comm/dotnetbbs/Showtopic.aspx?Forum_ID=5&Id=255629&PPage=21
在网上看到一些这样类似的问题却没有一个比较好的答案,这里给出一个方法给大家参考一下。

首先请看bingfeng那篇经典的《终于实现c#调用matlab函数》。

这里是我用matlab写的测试函数,做加法的。

//add.m
function result=add(left,right)
result=left + right;

//end of add.m

这里我做成的matlab dll叫做f_1_0.dll(顺便提一下,bingfeng的那个例子我运行不了,因为如果matlab函数
名字写成test,那么做com的时候就不能叫test了……我的版本是matlab 6。5)

下面是我的部分代码。

f.fClass st=new f.fClass();
object result;
int c=left;
int d=right;
result=new Object();
st.add(1,result,left,right);
int answer= (int) result;
return answer;

调用matlab的add函数做加法。
add在matlab中只有两个参数,在c#下有4个
函数声明是 void add(int nargout,ref object,object,object)
第一个是输出参数的个数(number of argument out)
第二是个用来输出计算结果的引用。
第3个和第4个分别是add在matlab中的参数,也就是left和right。

我才是一个大二的学生,帮着老师做一个算法的网上平台,所以写的水平肯定是很糟糕的,请大家见量。
前几天对.net还是一窍不通,如果不是bingfeng的这篇文章我是肯定做不下去的了。
下午通过microsoft的新闻组解决了这个问题。所以就想到了饮水思源,请bingfeng把它发出来。


这是newsgroup上的讨论:

suppose a simple matlab function
//add.m
function result=add(left,right)
result=left + right;

//end of add.m

use matlab comtool to encapsulate the function in fun.dll
and then use it in c#.net

i create a c# web service project to call
the matlab function add

but the function declaration has changed:
//create a instance;
fun.funClass st=new fun.funClass();

when i want to write st.add(parameters)

the declaration is
void add(int nargout,ref object,object,object)

which in matlab there're only two (left and right)

Could anyone please tell what's the meaning of int nargout and ref object?
And how to call the function add correctly?





Hi,
my guess is
nargout is number of output arguments
ref object will hold the result
the two 'val' objects are the input parameters
So I would be looking for C# code something like
object myResult;
int num1 =5;
int num2 =6;
st.add(1,myResult,num1,num2)
ie the following c# is similar in intent
private void button1_Click(object sender, EventArgs e)

{

int x = 5;

int y = 6;

object myResult;

myResult = new object();

Addem(ref myResult,x,y);

int z;

if( int.TryParse(myResult.ToString(),out z))

MessageBox.Show(" Result is " + z.ToString());

}

private void Addem(ref object myResult, int x, int y)

{

myResult = x + y;

}

HTH

bob(感谢这个叫bob的美国朋友,半个小时内就帮我解答了这个问题)


这个是微软的新闻组:msnews.microsoft.com,大家可以用outlook订阅它,里面有很多热心的朋友能互相交流和帮助。