问题描述
例如,如何将std::vector<std::byte>
转换为C样式函数的原始数据。这是完美的工作。
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); }
}
但是如何将我的字节向量提供给const unsigned char**
?我需要它用于功能SomeCApi(const unsigned char** buffer,unsigned int size)
。我尝试reinterpret_cast<const unsigned char**>(&bytes[0])
,但不起作用。
我收到异常“访问冲突读取位置”。
MSVC 19,c ++ 17(最新)。 我的情况:
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;
解决方法
要向接受vector<char>
的C函数提供const char**
,您可以访问内部缓冲区并返回指向它的指针:
#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
用于获取指向数组的指针的简单接口:
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());