如何在C函数中使用std :: vector [英] How to use a std::vector in a C function

查看:72
本文介绍了如何在C函数中使用std :: vector的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C函数希望在运行时将缓冲区数组纳入范围.例如

A C function expects an array of buffers to be in scope at runtime. e.g.

char values[x][y]

C函数将填充缓冲区
我想使用动态数组,因此不必对尺寸进行硬编码
在这种情况下如何使用std :: vector?

The C function will populate the buffers
I would like to use a dynamic array so I don't have to hard code the dimensions
How do I use a std::vector in this situation?

请明确一点,我正在使用C ++.C函数包含在我无法修改的库中.

Just to be clear, I am using C++. The C function is contained in a library that I cannot modify.

推荐答案

如果您只想将封装在 std :: vector 中的动态数组传递给 c 例程中,您可以将指针传递给基础数组的头部,如下所示:

If you just want to pass the dynamic array encapsulated in a std::vector to a c routine you can pass a pointer to the head of the underlying array as:

std::vector<char> myvector;
// size-up myvector as needed
foo(&myvector[0]); // pass a pointer to start of myvector to function foo

c ++ 标准可确保 std :: vector 中的基础数组始终是连续的.

The c++ standard ensures that the underlying array in std::vector is always contiguous.

希望这会有所帮助.

虽然声明 char values [x] [y] 创建一个数组数组",但 values 的内存实际上只是一个连续的块,本质上 char linear_values [x * y] .

While the declaration char values[x][y] creates an "array of arrays" the memory for values will actually just be a contiguous block, essentially char linear_values[x * y].

如果您将 std :: vector 的大小设置为包括 x * y 个元素,则应该为您提供相同的基础动态分配的数组空间.

If you size your std::vector to include a count of x * y elements it should give you the same underlying dynamically allocated array space.

c 函数将按行优先顺序访问数组,因此,第一行元素将排在第一位,然后是第二个完整行,等等...

The c function will access the array in row-major order, so the first row of elements will come first, followed by the second full row etc...

这篇关于如何在C函数中使用std :: vector的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆