将应用程序从 VB 重写为 C++ 并出现错误 0070

Rewrite application from VB to C++ and get error 0070

我正在将 COM 的客户端应用程序从 VB 重写为 C++:

VB

Private Sub Command1_Click()
Dim proxy As Person
Set proxy = New Person
proxy.FirstName = "Maxim"
proxy.LastName = "Donax"
proxy.Persist ("C:\myFile.xml")
End Sub

C++

#import "COM.tlb" raw_interfaces_only, raw_native_types, no_namespace, named_guids
#include <iostream>

int main()
{
    Person per; // error 0070
    per.FirstName = "Maxim"; // error 3365
    per.LastName = "Donax";// error 3365
    per.Persist(" C:\myFile.xml ");// error 3365
}

我收到一个错误 E0070:Incomplete type not allowed,它本身会产生错误 3365:Incomplete type not allowed of class "Person" in next strings

我知道我做错了什么,但我找不到正确的解决方案。请帮忙

COM.tlb:


using System.Xml.Serialization;
using System.IO;
using System.Runtime.InteropServices;

namespace COM
{
    [ClassInterface(ClassInterfaceType.None)]
    public class Person : System.EnterpriseServices.ServicedComponent, IPerson
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public bool IsMale { get; set; }
        public void Persist(string FilePath)
        {
            StreamWriter oFile = new StreamWriter(FilePath);
            XmlSerializer oXmlSerializer = new XmlSerializer(typeof(Person));
            oXmlSerializer.Serialize(oFile, this);
            oFile.Flush();
            oFile.Close();
        }
        static public Person Retrieve(string FilePath)
        {
            StreamReader oFile = new StreamReader(FilePath);
            XmlSerializer oXmlSerilizer = new XmlSerializer(typeof(Person));
            Person oPerson = oXmlSerilizer.Deserialize(oFile) as Person;
            return oPerson;

        }
    }
}

IPerson.cs

using System;
namespace COM
{
    public interface IPerson
    {
        string FirstName { get; set; }
        bool IsMale { get; set; }
        string LastName { get; set; }

        void Persist(string FilePath);
    }
}

您必须学习一些 C++ 才能做到这一点。

还可以查看 Visual Studio 在输出文件夹中生成的 .tlh(可能还有 .tli)文件。

因此,下面是如何实例化和调用 COM 对象(例如使用 comdef.h 中的 Windows SDK tools/wrappers,如 _bstr_t):

#include <windows.h>
#import "COM.tlb" raw_interfaces_only, raw_native_types, no_namespace, named_guids

int main()
{
    CoInitialize(NULL);
    {
        IPersonPtr per(__uuidof(Person)); // equivalent of CoCreateInstance(CLSID_Person,..., IID_IPerson, &person)
        per->put_FirstName(_bstr_t(L"Maxim"));
        per->put_LastName(_bstr_t(L"Donax"));
        per->Persist(_bstr_t(L"c:\myFile.xml"));
    }
    CoUninitialize();
    return 0;
}

或者更简单一点(使用自动生成的方便的包装器):

#include <windows.h>
#import "COM.tlb"

using namespace COM; // your namespace, COM is probably not a good namespace name

int main()
{
    CoInitialize(NULL);
    {
        IPersonPtr per(__uuidof(Person));
        per->PutFirstName(L"Maxim");
        per->PutLastName(L"Donax");
        per->Persist(L"c:\myFile.xml");
    }
    CoUninitialize();
    return 0;
}