diff --git a/mssql_python/pybind/ddbc_bindings.cpp b/mssql_python/pybind/ddbc_bindings.cpp index 4e7e8263..75311b8f 100644 --- a/mssql_python/pybind/ddbc_bindings.cpp +++ b/mssql_python/pybind/ddbc_bindings.cpp @@ -8,6 +8,7 @@ #include "connection/connection_pool.h" #include +#include // For std::memcpy #include // std::setw, std::setfill #include #include // std::forward @@ -2463,10 +2464,11 @@ static py::object FetchLobColumnData(SQLHSTMT hStmt, } else { // Wide characters size_t wcharSize = sizeof(SQLWCHAR); - if (bytesRead >= wcharSize) { - auto sqlwBuf = reinterpret_cast(chunk.data()); + if (bytesRead >= wcharSize && (bytesRead % wcharSize == 0)) { size_t wcharCount = bytesRead / wcharSize; - while (wcharCount > 0 && sqlwBuf[wcharCount - 1] == 0) { + std::vector alignedBuf(wcharCount); + std::memcpy(alignedBuf.data(), chunk.data(), bytesRead); + while (wcharCount > 0 && alignedBuf[wcharCount - 1] == 0) { --wcharCount; bytesRead -= wcharSize; } @@ -2495,14 +2497,18 @@ static py::object FetchLobColumnData(SQLHSTMT hStmt, } if (isWideChar) { #if defined(_WIN32) - std::wstring wstr(reinterpret_cast(buffer.data()), buffer.size() / sizeof(wchar_t)); + size_t wcharCount = buffer.size() / sizeof(wchar_t); + std::vector alignedBuf(wcharCount); + std::memcpy(alignedBuf.data(), buffer.data(), buffer.size()); + std::wstring wstr(alignedBuf.data(), wcharCount); std::string utf8str = WideToUTF8(wstr); return py::str(utf8str); #else // Linux/macOS handling size_t wcharCount = buffer.size() / sizeof(SQLWCHAR); - const SQLWCHAR* sqlwBuf = reinterpret_cast(buffer.data()); - std::wstring wstr = SQLWCHARToWString(sqlwBuf, wcharCount); + std::vector alignedBuf(wcharCount); + std::memcpy(alignedBuf.data(), buffer.data(), buffer.size()); + std::wstring wstr = SQLWCHARToWString(alignedBuf.data(), wcharCount); std::string utf8str = WideToUTF8(wstr); return py::str(utf8str); #endif @@ -2623,8 +2629,7 @@ SQLRETURN SQLGetData_wrap(SqlHandlePtr StatementHandle, SQLUSMALLINT colCount, p uint64_t numCharsInData = dataLen / sizeof(SQLWCHAR); if (numCharsInData < dataBuffer.size()) { #if defined(__APPLE__) || defined(__linux__) - const SQLWCHAR* sqlwBuf = reinterpret_cast(dataBuffer.data()); - std::wstring wstr = SQLWCHARToWString(sqlwBuf, numCharsInData); + std::wstring wstr = SQLWCHARToWString(dataBuffer.data(), numCharsInData); std::string utf8str = WideToUTF8(wstr); row.append(py::str(utf8str)); #else