它研究了如何将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]),但它不起作用。我得到异常“访问冲突读取位置”。
MSVC19,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;发布于 2020-09-16 20:26:59
要向接受const char**的C函数提供vector<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());https://stackoverflow.com/questions/63918733
复制相似问题