0

我为自己创建了一个小演示来练习结合 C++ 和 C#(对我来说是一项非常理想的技能)。
它看起来像这样:

类图

问题源于该类Person具有 type 的成员这一事实Name
将这些类公开给 C# 的正确方法是什么?

例如,我将如何公开这个构造函数:

    Person(Name name);

这有点难以解释,但问题是这个Person构造函数接受一个Name本机对象,我不能在 C# 中创建这个本机对象并将它传递给构造函数,对吧?它甚至是不可取的。
即使我为它编写了一个包装器(比如ManagedName),我也无法将它传递给它,Person因为没有可接受的构造函数。

我该如何应对这种情况?

以下是所要求的标题:

可空:http://pastebin.com/z7zTCrAq
名称:http
://pastebin.com/ALNp5c1a 人员: http: //pastebin.com/nkWyUv9C

4

1 回答 1

1

这是一种方法(C++/CLI)


class Name {
public:
    std::string firstName;
    std::string middleName;
    std::string lastName;
};
ref class ManagedName {
internal:
    Name* nameptr;
public:

    ManagedName() {
        nameptr = new Name();
    }
    ManagedName(System::IntPtr ptr) {
        nameptr = (Name*)(void*)ptr;
    }
    property System::String^ firstName {
        System::String^ get() {
            return gcnew System::String(nameptr->firstName.data());
        }
        void set(System::String^ val) {
            System::IntPtr strptr = System::Runtime::InteropServices::Marshal::StringToBSTR(val);
            nameptr->firstName = (char*)(void*)strptr;
            System::Runtime::InteropServices::Marshal::FreeBSTR(strptr);
        }
    };
    property System::String^ middleName {
        System::String^ get() {
            return gcnew System::String(nameptr->middleName.data());
        }
        void set(System::String^ val) {
            System::IntPtr strptr = System::Runtime::InteropServices::Marshal::StringToBSTR(val);
            nameptr->middleName = (char*)(void*)strptr;
            System::Runtime::InteropServices::Marshal::FreeBSTR(strptr);
        }
    };
    property System::String^ lastName {
        System::String^ get() {
            return gcnew System::String(nameptr->lastName.data());
        }
        void set(System::String^ val) {
            System::IntPtr strptr = System::Runtime::InteropServices::Marshal::StringToBSTR(val);
            nameptr->lastName = (char*)(void*)strptr;
            System::Runtime::InteropServices::Marshal::FreeBSTR(strptr);
        }
    };
};
class Person {
public:
    Name* name;
    std::string birthday;
    Person(Name* name) {
        this->name = name;
    }
};
ref class ManagedPerson {
public:
    ManagedPerson(ManagedName^ name) {
        //create an instance of the native class
        personPtr = new Person(name->nameptr);

    }
    property System::String^ Birthday {
        System::String^ get() {
            return gcnew System::String(personPtr->birthday.data());
        }

    };
    property ManagedName^ Name {
        ManagedName^ get() {
            return gcnew ManagedName(System::IntPtr(personPtr->name));
        }
    };
private:
    Person* personPtr;
};

于 2013-06-10T02:50:56.103 回答