I have two libraries, from C++ and C, respectively:
lib A in C++:
typedef struct {
char val[4096];
} AString;
lib B in C:
typedef struct STRING_TYPE{
unsigned char *u1_list;
signed int i4_length;
} BString;
If I cannot touch lib A & B code, i.e., cannot add a cast operator in AString class. How to convert from AString to BString?
EDIT 1: no separate function defined:
AString as=XXX; // given variable 'as' to convert,
unsigned char p[4096];
size_t const N = std::min(strlen(as.val), 4096);
BString bs = { p, N };
std::copy( static_cast<unsigned char*>(&as.val[0]), static_cast<unsigned char*>(&as.val[N]), bs.u1_list );
// or use memcpy like:
memcpy (bs.u1_list, as.val, N+1);
// then follows the part to use converted variable bs;
func(bs);
but the code is not module structured.
or else:
EDIT 2: which is essentially EDIT_1, define a function,
void convert (AString& as, BString& bs)
{
size_t const N = std::min(strlen(as.val), 4096);
std::copy( static_cast<unsigned char*>(&as.val[0]), static_cast<unsigned char*>(&as.val[N]), bs.u1_list );
// or use memcpy like:
memcpy (bs.u1_list, as.val, N+1);
bs.i4_length = N;
}
but before call this function, the user has to define an array, like
AString as=XXX; // given variable 'as' to convert,
unsigned char p[4096];
BString bs;
bs.u1_list = p;
convert(as, bs);
// then follows the part to use converted variable bs;
func(bs);
Both are quite awkward.
Isn’t there any self-contained, separate-function way to do this?
Something like this:
Be sure to document the fact that this memory can now be leaked. Both types seem like strange things to pass around in C++, to be honest; what’s wrong with
std::string?