How to use a std::vector in a C function
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 us开发者_如何学JAVAe 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.
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...
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
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.
精彩评论