C#调用C++dll问题,大家不要错过哦(你要是把这个问题弄明白了,互操作调用C++dll的就全活了),
我这里的代码样子都是表示个意思,实际比这复杂多了,但是基本同理(请不要试图编译这个代码,你要是编译,可能需要修改修改,我直接在notepad写的)
dll的输出头文件定义:
//对象驱动接口,仅仅是接口,没有export,因为提供了头文件,应用程序可以使用
class CClassCallback
{
public:
virture HRESULT OnAdded() = 0;
virture HRESULT OnDeled() = 0;
virture HRESULT OnFailed() = 0;
};
//
struct SAtype
{
CString strTest;
int nTest;
CClassCallback* pClassCallback;
};
//类接口,类似COM的接口,没有export,因为提供了头文件,应用程序可以使用
class CTestInterface
{
public:
virture HRESULT Test1(SAtype* pTest) = 0;
virture HRESULT Test2() = 0;
virture void Release() = 0;
};
输出函数export:CTestInterface* ConstructInterface(); //仅仅这个函数是输出的
在dll的实现类似如下:
class CTestObject:public CTestInterface
{
public:
HRESULT Test1(SAtype* pTest)
{
m_sType = *pTest;
}
HRESULT Test2()
{
}
void Release()
{
delete this;
}
private:
void InnerDemoFuc()
{
if(true)
{
m_sType.pClassCallback->OnAdded();
}
}
SAtype m_sType;
}
CTestInterface* ConstructInterface()
{
return new CTestObject();
}
在C++的App中一般这么使用:
(1)派生一个CClassCallback子类
class CClassCallbackEx:public CClassCallback
{
public:
CClassCallbackEx();
virture HRESULT OnAdded()
{
.....//干些通知的业务的活
}
virture HRESULT OnDeled()
{
}
virture HRESULT OnFailed()
{
}
}
(2)如下使用:
CTestInterface* m_pInterface = ConstructInterface(); //调用输出函数创建对象,获取外部接口
SAtype sAtype;
sAtype->pClassCallback = new CClassCallbackEx(); //设置回调驱动对象(我使用对象驱动,非函数驱动)
m_pInterface->Test1(&sAtype); //调用某个函数
。。。。。
m_pInterface->Relese();
m_pInterface=NULL; //在合适的时候释放对象
现在我要想在C#的界面程序中使用这个dll,这么弄啊?
我搜了一下,如果我这个东西弄好的话,所以C#调用C++的dll技术都全活了
解决方案
Invoke Native C++ DLL from .NET Code
http://blogs.msdn.com/b/codefx/archive/2010/05/02/invoke-native-c-dll-from-net-code.aspx
介绍够详细的。
用户评论