简体   繁体   English

将C ++ / CLI中的动态对象返回到C#

[英]Return dynamic object in C++/CLI to C#

I've got a C++/CLI project that wraps a large number of classes - and the classes have their own meta-data system. 我有一个包含大量类的C ++ / CLI项目 - 这些类有自己的元数据系统。 So I'd like to return a dynamic object to make some use cases easy in C#. 所以我想返回一个动态对象,以便在C#中简化一些用例。 But I don't see how to do this in C++. 但我不知道如何在C ++中这样做。

In C# I can write the following: 在C#中我可以写下面的内容:

dynamic TestThisOut()
{
    return null;
}

void mork()
{
    var d = TestThisOut();
    d.Fork();
}

I would like to write TestThisOut() in C++/CLI, so that I can use it exactly the same way as I do in the "mork" function above (ie not having to type the dynamic keyword). 我想在C ++ / CLI中编写TestThisOut() ,这样我就可以像在上面的“mork”函数中那样使用它(即不必键入dynamic关键字)。 Is this possible? 这可能吗?

You can create a dynamic object in c++/cli, you just can't consume it there as you would in C# project. 可以在c ++ / cli中创建一个动态对象,就像在C#项目中一样,你不能在那里使用它。 However you can consume it from C#. 但是你可以从C#中使用它。 Here is how you do it: 这是你如何做到的:

In C++/CLI create a property or a method that returns Object^ . 在C ++ / CLI中,创建一个返回Object ^的属性或方法。 Mark this property or method with System::Runtime::CompilerServices::DynamicAttribute . 使用System :: Runtime :: CompilerServices :: DynamicAttribute标记此属性或方法。 You are good to go. 你已准备好出发。

Here is a quick sample I created: 这是我创建的一个快速示例:

namespace ClassLibrary1 
{
    using namespace System;
    using namespace System::Dynamic;

    public ref class Class1 : public DynamicObject
    {
    public:
        [System::Runtime::CompilerServices::Dynamic]
        static property Object^ Global
        {
        public:
            Object^ get()
            {
                return gcnew Class1();
            }
        }

    public:
        String^ Test()
        {
            return "Test";
        }
    };
}

And my C# consumer: 而我的C#消费者:

Console.WriteLine( ClassLibrary1.Class1.Global.Test() );

dyanmic is C# 4.0 keyword. dyanmic是C#4.0关键字。 It is not supported in C++ CLI (and also in VB.NET ). 它在C ++ CLI(以及VB.NET )中不受支持。

If you want to consume dynamic object in C++ CLI, then you can use impromptu-interface library. 如果要在C ++ CLI中使用动态对象,则可以使用即兴接口库。 List of supported options . 支持的选项列表 Information is from this question 信息来自这个问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM