Skip to content

Commit

Permalink
add support for std::wstring following std::string (#562)
Browse files Browse the repository at this point in the history
  • Loading branch information
kayama-shift authored May 22, 2024
1 parent 58c7834 commit 26373d5
Showing 1 changed file with 39 additions and 0 deletions.
39 changes: 39 additions & 0 deletions include/nanobind/stl/wstring.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
/*
nanobind/stl/string.h: type caster for std::string

Copyright (c) 2022 Wenzel Jakob

All rights reserved. Use of this source code is governed by a
BSD-style license that can be found in the LICENSE file.
*/

#pragma once

#include <nanobind/nanobind.h>
#include <string>

NAMESPACE_BEGIN(NB_NAMESPACE)
NAMESPACE_BEGIN(detail)

template <> struct type_caster<std::wstring> {
NB_TYPE_CASTER(std::wstring, const_name("str"))

bool from_python(handle src, uint8_t, cleanup_list *) noexcept {
Py_ssize_t size;
const wchar_t *str = PyUnicode_AsWideCharString(src.ptr(), &size);
if (!str) {
PyErr_Clear();
return false;
}
value = std::wstring(str, (size_t) size);
return true;
}

static handle from_cpp(const std::wstring &value, rv_policy,
cleanup_list *) noexcept {
return PyUnicode_FromWideChar(value.c_str(), value.size());
}
};

NAMESPACE_END(detail)
NAMESPACE_END(NB_NAMESPACE)

0 comments on commit 26373d5

Please sign in to comment.