c# - 从 C++ dll 编码导出的字符串 vector

标签 c# c++

如何编码从 C++ dll 导出的字符串 vector ?我希望在我的 C# 程序中使用它们之前将它们分开。你能帮帮我吗?

最佳答案

是的。你可以。其实不只是std::vector , std::string , std::wstring , 任何标准 C++ 类或您自己的类都可以被编码(marshal)或实例化,并从 C#/.NET 调用。

包装 std::vector<any_type>在 C# 中确实可以只使用常规的 P/Invoke Interop,但它很复杂。甚至任何类型的 std::map 都可以在 C#/.NET 中完成。

从 .NET 世界实例化 C++ 对象的基本思想是从 .NET 中分配 C++ 对象的精确大小,然后调用从 C++ DLL 导出的构造函数来初始化对象,然后您将能够调用任何函数来访问该 C++ 对象,如果任何方法涉及其他 C++ 类,您也需要将它们包装在 C# 类中,对于具有原始类型的方法,您可以简单地 P/Invoke 它们。如果调用的方法只有几个,那就简单了,手工编码不会花很长时间。当你完成 C++ 对象时,你调用 C++ 对象的析构函数方法,这也是一个导出函数。如果它没有,那么您只需要从 .NET 中释放您的内存。

这是一个例子。

public class SampleClass : IDisposable
{    
    [DllImport("YourDll.dll", EntryPoint="ConstructorOfYourClass", CharSet=CharSet.Ansi,          CallingConvention=CallingConvention.ThisCall)]
    public extern static void SampleClassConstructor(IntPtr thisObject);

    [DllImport("YourDll.dll", EntryPoint="DoSomething", CharSet=CharSet.Ansi,      CallingConvention=CallingConvention.ThisCall)]
    public extern static void DoSomething(IntPtr thisObject);

    [DllImport("YourDll.dll", EntryPoint="DoSomethingElse", CharSet=CharSet.Ansi,      CallingConvention=CallingConvention.ThisCall)]
    public extern static void DoSomething(IntPtr thisObject, int x);

    IntPtr ptr;

    public SampleClass(int sizeOfYourCppClass)
    {
        this.ptr = Marshal.AllocHGlobal(sizeOfYourCppClass);
        SampleClassConstructor(this.ptr);  
    }

    public void DoSomething()
    {
        DoSomething(this.ptr);
    }

    public void DoSomethingElse(int x)
    {
        DoSomethingElse(this.ptr, x);
    }

    public void Dispose()
    {
        Marshal.FreeHGlobal(this.ptr);
    }
}

详情请见以下链接

C#/.NET PInvoke Interop SDK

(我是SDK工具的作者)

关于c# - 从 C++ dll 编码导出的字符串 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7883781/

相关文章:

c# - 为什么我的文件上传控件不能正常工作

c++ - C++ 简介 : Sorting code

c++ - 创建缝合对象会导致错误

c++ - 在嵌套类中调用私有(private)函数

c# - 如何延迟我的打印功能以便我可以看到每个对象的打印时间

c# - VS2015 Enterprise 上下文菜单中没有 'run IntelliTest' 选项

c# - 使用 Zebra 打印机打印多个不同的标签

c++ - 如何处理可选参数的模板类型名?

c++ - 无限循环直到应用程序收到信号

c# - 嵌套的 gridview 获取父行