How to use a std::vector in a C function

允我心安 提交于 2019-12-01 04:44:24

问题


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

char values[x][y]

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?

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


回答1:


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

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

Hope this helps.

EDIT: 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].

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.

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...




回答2:


C doesn't have standard data structures libraries.

If you really want all the functionality of a vector, and it's not for something critical, you can probably find someone's pet implementation of a straight C vector online and just use that.

If it is critical, write your own. It's not too hard, and can be quite useful.

If you just want a dynamically growing array, it's easy to emulate that behavior of a vector using the realloc function, which extends the dimensions of a heap-allocated array. Start with a small array, and grow as needed when you reach the end. It's more efficient to grow in big chunks, but if you have some idea of what your data looks like you could grow it in a different way. A common method is doubling the array size every time you run out.

You can get the details of realloc at:

http://www.cplusplus.com/reference/clibrary/cstdlib/realloc/

or, on a *nix system:

man realloc




回答3:


You can't.

By definition, C knows nothing of any of the required components of a std::vector, including, but not limited to:

  • C does not have namespaces, so it can't understand the std namespace.

  • C does not have templates, so it can't understand the std::vector<T> type.

Essentially, you need what looks like a C function, but that is, for all intents and purposes, a C++ function.

The simplest way to achieve this is probably to write what looks like a C function, using C++, and running the whole mess through a C++ compiler rather than a C compiler.



来源:https://stackoverflow.com/questions/6701816/how-to-use-a-stdvector-in-a-c-function

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!