通过COM将c ++中的复杂对象传递给c#

时间:2011-06-20 03:31:03

标签: c# c++ interop com-interop

这个问题扩展了现有的问题:
Passing an object from C++ to C# though 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);

谢谢。

1 个答案:

答案 0 :(得分: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; }
}