Reputation: 23831
I have the following wrapper to expose my C++ code to C#
extern "C" {
LIBRARY_API void GenerateTables(
const char* version,
const char* baseDir,
const char** fileList);
} // end extern "C"
void GenerateTables(
const char* version,
const char* baseDir,
const char** fileList)
{
std::string strVersion(version);
std::string strBaseDir(baseDir);
// I now need to convert my const char** to std::vector<std::string>
// so it can be passed to another internal method.
}
How can I convert my const char** fileList
to std:vector<std::string>
. I am relatively new to C++ and there is a clear problem with memory allocation here. I could do something like
std::vector<std::string> vec;
for (int i = 0; i < fileList.length() /* length() of what!? */; i++)
vec.push_back(/* what!? */);
How can I do the required conversion and is there a better way of passing in an array of strings (string[]
) from C# to C++ via interop?
Thanks for your time.
Upvotes: 1
Views: 1880
Reputation: 613302
You need to give the unmanaged code some way to obtain the length. There are two commonly used approaches:
Either option is simple enough for you to implement. The choice is entirely down to your personal preference.
If you choose the first option then you can populate the vector like this:
std::vector<std::string> files(fileList, fileList + length);
If you choose the second option then you'd use a loop like this:
std::vector<std::string> files;
const char** filePtr = fileList;
while (*filePtr != nullptr)
files.push_back(*filePtr++);
Upvotes: 4
Reputation: 2057
You need to know the length of fileList
array. Once you know it you can convert fileList
using
size_t length = ... ;
std::vector<std::string> files( fileList, fileList + length );
Upvotes: 1