Reputation: 107
It's examle how convert std::vector<std::byte>
to raw data for C-style function. It's perfect work.
void SomeCApi(unsigned char* buffer, unsigned int size)
{
for (unsigned char index = 0; index < size; ++index) {
buffer[index] = index;
}
}
int main()
{
std::vector<std::byte> buffer{ 100 };
SomeCApi(reinterpret_cast<unsigned char*>(&buffer[0]), buffer.size());
for (const auto& element : buffer) { PrintByte(element); }
}
But how I can provide my bytes vector to const unsigned char**
?? Me need it for function SomeCApi(const unsigned char** buffer, unsigned int size)
. My try reinterpret_cast<const unsigned char**>(&bytes[0])
, but it's not work.
I get exception "Access violation reading location".
MSVC 19, c++17(latest). My case:
unsigned char* sig;
sig = (unsigned char*)alloca(signature_len);
std::vector<std::byte> bytes(signature_len);
ec_sig = d2i_ECDSA_SIG(NULL, reinterpret_cast<const unsigned char**>(&bytes[0]), signature_len); //It's throw Access violation reading location
//ec_sig = d2i_ECDSA_SIG(NULL, (const unsigned char**)&sig, signature_len); //It's perfect work with C-Style raw data and C-style cast.
if (ec_sig == NULL)
std::cout << "BAD" << std::endl;
Upvotes: 0
Views: 564
Reputation: 14815
To provide a vector<char>
to a C function accepting const char**
you can access the internal buffer and return a pointer to it:
#include <iostream>
#include <vector>
void someCApi(const char** c, size_t len)
{
for (size_t i=0; i<len; ++i)
{
std::cout << static_cast<int>((*c)[i]) << std::endl;
}
}
auto main() -> int
{
std::vector<char> buff{1,3,5,7,11,13,17,19};
const char* buffPtr = buff.data();
someCApi(&buffPtr, buff.size());
return 0;
}
https://onlinegdb.com/B1BSNKyrv
Simple interface to get the pointer to array:
template <typename T>
class pptr
{
const T* buff=nullptr;
public:
ppta(std::vector<T>& v): buff(v.data()){};
const T** operator()(){return &buff;}
};
//Usage
someCApi(pptr(buff)(), buff.size());
Upvotes: 1