c# - 如何将 vector<double> 从 C++ 编码到 C#

标签 c# c++ vector marshalling

我目前的解决方法是,从 C# 中使用以下方法获取 vector 的大小:

[DllImport("BridgeInterface.DLL", EntryPoint = "#46", SetLastError = true, CharSet = CharSet.Ansi, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl]
private static extern int GetVectorSize();

其中 BridgeInterface.dll 是我的 C++ 和 C# 代码之间的 C++ 桥接口(interface)。然后我使用以下方法编码每个 vector 元素:

[DllImport("BridgeInterface.DLL", EntryPoint = "#47", SetLastError = true, CharSet = CharSet.Ansi, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl]
private static extern double GetVectorElement(int index);

有没有办法使用一次 C++ 调用来编码整个 vector ?

最佳答案

std::vector<>,根据标准,必须驻留在连续的内存空间中。所以你所有的 double 都在一个内存块中,所以它可以被编码为一个内存缓冲区(获取指向第一个元素的指针并执行 size() * sizeof(double) 缓冲区的长度)。之后它被简化为编码 double 数组的情况,我发现 this发布解释如何(有和没有复制到 C# 内存空间)。

关于c# - 如何将 vector<double> 从 C++ 编码到 C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22092217/

相关文章:

c++ - 头文件中的 QList 声明导致源文件中出现段错误

抽象类 vector 的C++ vector

c++ - 遍历 vector 并删除内容

c# - 使用 windows api 读取应用程序的当前安装版本

c# - 访问WPF DLL的ViewModel

c# - 不显示wpf边框之外的内容

android - Necessitas SDK for android app with Qt

c++ - 数组搞砸了 C++

.net - 如何构建 system::drawing::rectangle 的 vector

c# - 如何使用 Newtonsoft.Json 序列化 C# ref 字段?