我有 COM 组件 (dll) ThirdParty 定义了接口(interface) 和一些实现此接口(interface)的 COM 类 ThirdPartyObjectClass。 我有适当的文件 ThirdParty.h 和 ThirdParty_i.c 允许用 C++ 编译它。
IThirdParty { HRESULT ComFoo(); }
我使用“tlbimp/sysarray”构建了名为 ThirdPartyInterop.dll 的互操作 dll, 公开 .Net 接口(interface) ThirdPartyObject
我编写了新的 C# 组件,它引用了 ThirdPartyInterop.dll
using ThirdPartyInterop; namespace CsComponent { public class CsClass { public void NetFoo( ThirdPartyObject thirdPrty ) { thirdPrty.ComFoo(); } } }
ThirdPartyClass 的元数据是:
using System.Runtime.InteropServices;
namespace ThirdPartyInterop
{
[CoClass(typeof(ThirdPartyObjectClass))]
[Guid("xxxx")]
public interface ThirdPartyObject : IThirdParty
{
}
}
和
using System;
using System.Runtime.InteropServices;
namespace ThirdPartyInterop
{
[TypeLibType(4160)]
[Guid("yyyy")]
public interface IThirdParty
{
[DispId(1)]
void ComFoo();
}
}
我有一个用托管 C++ 编写的旧代码。
with the following:
#include "stdafx.h"
#pragma managed(push, off)
#include "ThirdParty_i.c"
#include "ThirdParty.h"
#pragma managed(pop)
void CppFoo( IThirdParty* thirdParty )
{
...
thirdParty -> ComFoo();
...
}
我需要更改它以使用我的 CsClass:
#include "stdafx.h"
#pragma managed(push, off)
#include "ThirdParty_i.c"
#include "ThirdParty.h"
#pragma managed(pop)
void CppFoo( IThirdParty* thirdParty )
{
...
//thirdParty -> ComFoo();
CsComponent::CsClass^ csClass = gcnew CsComponent::CsClass();
csClass.NetFoo( thirdParty );
...
}
但这无法编译: 错误 C2664:“CsComponent::CsClass::NetFoo”:无法将参数 1 从“ITirdParty *”转换为“ThirdPartyInterop::ThirdPartyObject ^”
下面的实现是可以的:
#include "stdafx.h"
#pragma managed(push, off)
#include "ThirdParty_i.c"
#include "ThirdParty.h"
#pragma managed(pop)
void CppFoo( IThirdParty* thirdParty )
{
...
//thirdParty -> ComFoo();
CsComponent::CsClass^ csClass = gcnew CsComponent::CsClass();
ThirdPartyInterop::ThirdPartyObject^ _thirdParty = gcnew ThirdPartyInterop::ThirdPartyObject();
//csClass.NetFoo( thirdParty );
csClass.NetFoo( _thirdParty );
...
}
但我需要使用 CppFoo 的参数 thirdParty。
我的问题是:
如何从给定的 ITirdParty* 创建 ThirdPartyInterop::ThirdPartyObject?
最佳答案
因为在您的情况下,每个 ITirdParty 实际上都是一个 ThirdPartyObject,您可以只使用强制转换。然而,除了在新指令中,你永远不应该使用 com 对象的具体类型,总是只使用接口(interface)。更改您的 NetFoo() 方法以将 ITirdParty 作为参数。
关于c# - 错误 C2664 - 需要帮助和说明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24925132/