c# - 如何从非托管 C++ 代码获取结构化列表值到 C#?

标签 c# c++ com interop marshalling

我正在用 win32 c++ 编写“ICS/VCS”文件解析器。

从文件反序列化后,我将事件数据存储在事件结构列表中。

现在我想在 C# 中访问该结构化列表。 为此,我在 DLL 中导出了函数和列表。

我不知道如何在 C# 中访问该列表。

这是我的事件结构:

struct Event {
Event(): Alarms(new list<Alarm>), RecurrenceNo(0), BaseEvent(this) {}
Event(const Event &Base) :
    UID(Base.UID),
    Organizer(Base.Organizer),
    Summary(Base.Summary),
    Description(Base.Description),
    Attendee(),
    Categories(Base.Categories),
    DtStamp(Base.DtStamp),
    DtStart(Base.DtStart),
    DtEnd(Base.DtEnd),
    RRule(Base.RRule),
    Alarms(Base.Alarms),
    AttendeeCounter(Base.AttendeeCounter),
    RecurrenceNo(Base.RecurrenceNo)

{
    BaseEvent = Base.BaseEvent == (Event *)&Base ? (Event *)&Base : Base.BaseEvent;
}
~Event() {
    if (BaseEvent == this)
        delete Alarms;
}
operator string() const;
bool HasAlarm(const Date &From, const Date &To);

string UID, Summary, Description, Categories, Attendee[100], Organizer;
int AttendeeCounter=0;
Date DtStamp, DtStart, DtEnd;
Recurrence RRule;
list<Alarm> *Alarms;
unsigned short RecurrenceNo;
Event *BaseEvent;
};

这是 ExportFunction.h

extern list <Event *> ListofAllEvents;
extern "C" __declspec(dllexport) list <Event *> ParseCalendar(std::string FilePath);

这是我要导出的函数 “ExportFunction.cpp

list <Event *> ParseCalendar(std::string FilePath)
{
const char * InputPath = FilePath.c_str();

ICalendar Calendar(InputPath);
return ListofAllEvents;
}

这是Program.cs

    [DllImport("D:\\Projects\\iCalander\\x64\\Debug\\iCalander.dll", CallingConvention = CallingConvention.Cdecl)]
    public static extern IntPtr ParseCalendar(string FilePath);

它显示访问冲突错误。这是预期的,因为我没有正确访问。

我是 pInvoke 和编码的新手。

最佳答案

如果有人想做同样的事情,请回答我自己的问题以供将来引用。

我按照本教程进行了实验并了解了互操作性。

https://www.red-gate.com/simple-talk/dotnet/net-development/creating-ccli-wrapper/

https://www.red-gate.com/simple-talk/dotnet/.net-framework/5-tips-for-understanding-managed-unmanaged-interoperability-in-.net/?_ga=2.110977479.318099589.1504532675-232460203.1501855788

然后我将事件结构的原型(prototype)类实现到 c++/cli 中。

public ref class iCalendarEvent 
{
public:
    String ^mUID;
    String ^mOrgaizer;
    String ^mSummary;
    String ^mDescription;
    String ^mCategories;
    String ^mDtStart;
    String ^mDtEnd;
    String ^mDtStamp;
    cli::array<String ^>^ mAttendee = gcnew cli::array<String ^>(100);
    int mAttendeeLength;

};

然后创建了一个 iCalendarEvent 类型的通用列表。然后,我将每个从 c++ 返回的事件对象映射到 c++/cli 的类 obj 中,并将其插入到 c++/CLI 的通用列表中。

关于c# - 如何从非托管 C++ 代码获取结构化列表值到 C#?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54400378/

相关文章:

vb.net - .NET & CreateObject,COM对象使用谁的内存?

c# - 使用 ReaderWriterLock 的真正缺点是什么

c++ - 在数组中查找数字

c++ - 是否有任何 DirectX 11 (HLSL 5.0) 等同于 DirectX 9 纹理 "string function"语法?

.net - 如何在 BackgroundWorker 中访问 COM 对象?

excel - 使用 Excel 的 ExportAsFixedFormat 失败

c# - Usercontrol不同控件属性访问

c# - 无法访问继承的全局变量

c# - double 格式 - 显示零位或两位小数

c++ - C++中线程的简单示例