【发布时间】:2010-11-24 18:39:49
【问题描述】:
我们面临互操作问题,我们正在用 C# 编写客户端 exe,我们有一些用 COM dll 编写的遗留代码和一个原生 C++ 静态库。 我们需要同时使用它们来完成 C# 客户端中的功能。我们使用互操作添加了对 COM dll 的引用,并且能够 在 C# 代码中创建 COM 类的实例。现在这个 COM 类方法接受的参数是 nactive C++ 的对象,COM 中的一些方法 类需要参数,这些参数是在 c++ 静态库中声明的类的对象。由于我们将无法创建 C++ 本地类的实例 C#,我们决定在原生类上编写 C++/CLI 包装器,并在 C# 代码中创建 warpper 的实例,并通过以下方式访问原生类的实例 warpper 并将其传递给在 C# 客户端中创建的 COM 类。问题是当我们将本地对象指针(作为 IntPtr)传递给 COM 类时,我们没有将本地对象初始化为其值。可能是什么问题呢?我们如何通过托管 c++ 包装器将原生对象传递回 C# 代码?
//Natvie C++ class
class __declspec(dllexport) CConfiguration
{
public :
CConfiguration(void);
virtual ~CConfiguration(void);
void SetIPAddress(const char *IPAddress);
void SetPort(const char*Port);
void GetIPAddress(char *IPAddress);
void GetPort(char *Port);
Private:
std::string IPAddress;
std::string Port;
}
//Managed C++ Class
public ref class ManagedConfigruation
{
public :
ManagedConfigruation(){}
~ManagedConfigruation(){}
CConfiguration *myConfiguration;
IntPtr GetObjectOfConfigurationPtr();
}
IntPtr ManagedConfigruation::GetObjectOfConfigurationPtr()
{
myConfiguration = new CConfiguration();
myConfiguration.SetIPAddress("127.0.0.1");
myConfiguration.SetPort("6200");
//Convert native object to IntPtr and return to C# class
return System::IntPtr(myConfiguration);
};
//C# class on client exe
public class CSharpClass
{
//Wrapper of Managed C++ class
ManagedConfiguration objManagedConfiguration = new ManagedConfiguration();
IntPtr objPtr = objManagedConfiguration.GetObjectOfConfigurationPtr();
//Belwoo COMObject needs object of type CConfiguration native C++ class
COMObject.Initialize(objPtr); //Here is the problem object does not contain anything
}
【问题讨论】:
-
不应该是
COMObject.Initialize(objPtr)吗? -
谢谢保罗纠正它