我创建了两个ATL Object,CTeacher和CStudentCStudent m_aStudent作为CTeacher的一个私有成员,并且为ITeacher添加了一个属性OneStudent用来访问
m_aStudent.简单源码如下:(省略了系统自动产生的很多代码)class CStudent
{
private:
long m_age;
public:
CStudent():m_age(10)
{
}
};class CTeacher
{
private:
IStudent* m_aStudent;
public:
CTeacher()
{
//创建Com对象实例
CoCreateInstance(CLSID_Student,NULL,CLSCTX_ALL,IID_IStudent, (void**)&m_aStudent);
}
}并且为其添加的IStudent *OneStudent属性:
STDMETHODIMP CTeacher::get_OneStudent(IStudent *pVal)
{
AFX_MANAGE_STATE(AfxGetStaticModuleState()) // TODO: Add your implementation code here
*pVal = * m_aStudent;
return S_OK;
}
STDMETHODIMP CTeacher::put_OneStudent(IStudent *newVal)
{
AFX_MANAGE_STATE(AfxGetStaticModuleState()) // TODO: Add your implementation code here
*m_aStudent = *newVal ;
return S_OK;
}现在我在vb中用如下代码测试,却出现错误。 Dim s As Student
Dim t As New Teacher
s = t.OneStudent最后一行语句
错误提示:function or interface ed as restricted ,or the function use an Automation type not supported in Visual Basic 我的理解是t.OneStudent返回的类型是IStudent,而s 是Student (为IStudent的继承类),所以类型不匹配。请问是这个原因吗??那要如何做才能实现类似的功能,就是从Com的CTeacher返回一个可以供vb使用的CStudent对象???我试过很多办法,都不能解决。哪位高手指点一下???
{
AFX_MANAGE_STATE(AfxGetStaticModuleState()) // TODO: Add your implementation code here
m_aStudent->AddRef;
*pVal = m_aStudent;
return S_OK;
}
{
AFX_MANAGE_STATE(AfxGetStaticModuleState()) // TODO: Add your implementation code here
m_aStudent->AddRef();
*pVal = m_aStudent;
return S_OK;
}
1.不管用不用ATL,如果是out-of-process server,则CoInitialize是必要的,in-process server因为有客户进程为它调CoInitialize
2.你可以把它定义为IDispatch,在方法内IStudent->QueryInterface(IID_Dispatch...)
在客户端,直接调就可以了,VB自动转换。
另外,put_OneStudent时要Release原接口。
象CoCreateInstance这类操作最好在父组件的FinalConstruct中调用,如果CoCreateInstance失败,则可以让FinalConstruct返回S_FALSE,这样将使客户端生成父组件失败。而构造函数是无法返回值的。