2011-06-20 37 views
1

這個問題擴展了現有的問題在這裏:
Passing an object from C++ to C# though COM經過一個複雜的對象在C++到C#通過COM

的一個簡單的物體前面的問題的交易,但我想對於一個複雜的對象做同樣的。

因此,而不是TestEntity1具有單個屬性,如果它具有另一個TestEntity2類型的屬性,如何分配C++消費者中的TestEntity1對象的TestEntity2類型的屬性?

C#:

using System; 
using System.Collections.Generic; 
using System.Text; 
using System.Runtime.InteropServices; 

namespace ClassLibrary1 
{ 
    [ComVisible(true)] 
    public interface ITestEntity1 
    { 
     string Name { get; set; } 
     TestEntity2 Entity2 { get; set; } 
    } 

    [ComVisible(true)] 
    public class TestEntity1 : ITestEntity1 
    { 
     public string Name { get; set; } 
    } 

    [ComVisible(true)] 
    public interface ITestEntity2 
    { 
     string Description { get; set; } 
    } 

    [ComVisible(true)] 
    public class TestEntity2 : ITestEntity2 
    { 
     public string Description { get; set; } 
    } 

    [ComVisible(true)] 
    public interface ITestGateway 
    { 
     void DoSomething(
      [MarshalAs(UnmanagedType.Interface)]object comInputValue); 
    } 

    [ComVisible(true)] 
    public class TestGateway : ITestGateway 
    { 
     public void DoSomething(object comInputValue) 
     { 
      if (!(comInputValue is TestEntity1)) 
      { 
       throw new ArgumentException("com input value", "comInputValue"); 
      } 

      TestEntity1 entity = comInputValue as TestEntity1; 
      //entity.Name 
      //entity.Entity2 
     } 
    } 
} 

C++:

// ComClient.cpp : Defines the entry point for the console application. 
// 

#include "stdafx.h" 
#import "..\Debug\ClassLibrary1.tlb" raw_interfaces_only 


int _tmain(int argc, _TCHAR* argv[]) 
{ 
    ITestGatewayPtr spTestGateway; 
spTestGateway.CreateInstance(__uuidof(TestGateway)); 

ITestEntity1Ptr spTestEntity1; 
spTestEntity1.CreateInstance(__uuidof(TestEntity1)); 

_bstr_t name(L"name"); 
spTestEntity1->put_Name(name); 

ITestEntity2Ptr spTestEntity2; 
spTestEntity2.CreateInstance(__uuidof(TestEntity2)); 

//spTestEntity1->putref_Entity2(spTestEntity2); //error C2664: 'ClassLibrary::ITestEntity1::putref_Entity2' : cannot convert parameter 1 from 'ClassLibrary::ITestEntity2Ptr' to 'ClassLibrary::_TestEntity2 *' 

spTestGateway->DoSomething(spTestEntity1); 

謝謝。

+0

是否有您要使用COM互操作的理由,而不是,例如,直接創建.NET包裝用C++/CLI?我發現這種方法要簡單得多,但你可能有不同的需求需要COM。 – jwismar

+0

@jwismar,不幸的是,我將使用遺留代碼來調用這個新的com對象,而且我現在沒有選擇使用託管的C++/cli重新編譯\ port。 –

+0

如果您在com服務器中包含typelib,則可以自動導入該接口 –

回答

2

我自己想通了。 :)

我不得不使用該接口來定義這樣的屬性:

[ComVisible(true)] 
public interface ITestEntity1 
{ 
    string Name { get; set; } 
    ITestEntity2 Entity2 { get; set; } 
} 

[ComVisible(true)] 
public class TestEntity1 : ITestEntity1 
{ 
    public string Name { get; set; } 
    public ITestEntity2 Entity2 { get; set; } 
}