A ByteArray
can be converted to a RawArray
:
ba = ByteArray[{1, 2, 3, 4}]
(* ByteArray[{1, 2, 3, 4}] *)
ra = RawArray["Byte", ba]
(* RawArray["UnsignedInteger8",{1, 2, 3, 4}] *)
Normal[ra]
(* {1, 2, 3, 4} *)
Presumably, this is done without unpacking the ByteArray contents to 64-bit integers first (although I have no proof of this).
Is there a similar space-efficient way to convert a rank-1 byte-type RawArray
to a ByteArray
?
Answer
At present there is no way to do this from top level, since there is no interface to the internal function that converts a rank-1 RawArray
of bytes into a ByteArray
.
However, as already pointed out, it's possible to take advantage of LibraryLink which will do a conversion given an MRawArray
on the C side and a "ByteArray"
return type, for example
Needs["CCompilerDriver`"]
src = "
#include \"WolframLibrary.h\"
#include \"WolframRawArrayLibrary.h\"
DLLEXPORT mint WolframLibrary_getVersion() {
return WolframLibraryVersion;
}
DLLEXPORT int WolframLibrary_initialize( WolframLibraryData libData) {
return 0;
}
DLLEXPORT void WolframLibrary_uninitialize( WolframLibraryData libData) {
return;
}
DLLEXPORT int mrawarray_to_bytearray( WolframLibraryData libData,
mint Argc, MArgument *Args, MArgument Res) {
WolframRawArrayLibrary_Functions rawFuns = libData->rawarrayLibraryFunctions;
MRawArray ra;
mint rank;
rawarray_t type;
if (Argc != 1) return LIBRARY_FUNCTION_ERROR;
ra = MArgument_getMRawArray(Args[0]);
type = rawFuns->MRawArray_getType(ra);
rank = rawFuns->MRawArray_getRank(ra);
if (rank == 1 && type == MRawArray_Type_Ubit8) {
MArgument_setMRawArray(Res, ra);
return LIBRARY_NO_ERROR;
}
return LIBRARY_FUNCTION_ERROR;
}";
lib = CreateLibrary[src, "toByteArray"];
toByteArray = LibraryFunctionLoad[lib,
"mrawarray_to_bytearray", {"RawArray"}, "ByteArray"];
toByteArray[RawArray["Byte", {1, 2, 3, 4}]]
(* ByteArray["AQIDBA=="] *)
Comments
Post a Comment