首页 > 代码库 > IDispatch接口 - 跨语言调用

IDispatch接口 - 跨语言调用

当一个COM接口支持IDispatch的时候(Dual接口),它就可以被其他语言调用。

这里我用perl试了一下。

perl测试代码

use warnings;
use strict;
use Win32::OLE;

use constant ADS_UF_ACCOUNTDISABLE => 2;
use constant ADS_SCOPE_SUBTREE => 2;

my $MyCom = Win32::OLE->new( "MyCom.MyCar" ) or die("Can't create object for MyCom");       

print "MyCom object:".$MyCom."\n";

my $total = 0;
 
$MyCom->AddGas(3, \$total);   
$MyCom->AddGas(4, \$total); 

print "Total gas: ".$total."\n";

my $Gas = $MyCom->{"Gas"};


print "Remain gas = ".$Gas."\n"; 
代码很简单,调用两次AddGas,然后读取com对象的属性。运行结果:


加了2次3和4,最终输出7,对。

但是这里有个问题,AddGas的第二个参数是输出参数,这里我不知道怎么填写,这个输出参数现在不工作。我没怎么花时间去查perl,但是从COM调用的角度来讲,已经成功了。


相关COM代码

STDMETHODIMP CMyCar::Run()
{
    // TODO: Add your implementation code here

    return S_OK;
}


STDMETHODIMP CMyCar::AddGas(LONG add, LONG* total)
{
    // TODO: Add your implementation code here
    m_Gas += add;
    *total = m_Gas;

    return S_OK;
}


STDMETHODIMP CMyCar::get_Gas(LONG* pVal)
{
    // TODO: Add your implementation code here
    *pVal = m_Gas;

    return S_OK;
}
注册表文件rgs:

HKCR
{
	MyCom.MyCar.1 = s 'MyCar Class'
	{
		CLSID = s '{5220D0BC-4702-43F9-9960-2D8ABE91896C}'
	}
	MyCom.MyCar = s 'MyCar Class'
	{
		CLSID = s '{5220D0BC-4702-43F9-9960-2D8ABE91896C}'
		CurVer = s 'MyCom.MyCar.1'
	}

	NoRemove CLSID
	{
		ForceRemove {5220D0BC-4702-43F9-9960-2D8ABE91896C} = s 'MyCom.MyCar'
		{
			ProgID = s 'MyCom.MyCar.1'
			VersionIndependentProgID = s 'MyCom.MyCar'

			ForceRemove Programmable
			InprocServer32 = s '%MODULE%'
			{
				val ThreadingModel = s 'Apartment'
			}
			TypeLib = s '{4B2C6C73-AD0D-466D-936D-B6BD8E7F7A2F}'
			Version = s '1.0'
		}
	}
}




IDispatch接口 - 跨语言调用