Skip to content

Is it valid to have both class_ & custom type_caster? #2836

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions tests/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,7 @@ set(PYBIND11_TEST_FILES
test_callbacks.cpp
test_chrono.cpp
test_class.cpp
test_class_custom_type_caster_mix.cpp
test_constants_and_functions.cpp
test_copy_move.cpp
test_custom_type_casters.cpp
Expand Down
42 changes: 42 additions & 0 deletions tests/test_class_custom_type_caster_mix.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
#include "pybind11_tests.h"

namespace pybind11_tests {
namespace class_custom_type_caster_mix {

class NumberStore {
private:
int stored;

public:
explicit NumberStore(int num) : stored{num} {}
int Get() const { return stored; }
};

} // namespace class_custom_type_caster_mix
} // namespace pybind11_tests

namespace pybind11 {
namespace detail {

using namespace pybind11_tests::class_custom_type_caster_mix;

template <>
struct type_caster<NumberStore> {
public:
PYBIND11_TYPE_CASTER(NumberStore,
_("pybind11_tests::class_custom_type_caster_mix::NumberStore"));

bool load(handle /*handle*/, bool /*convert*/) {
value = NumberStore(5);
return true;
}
};

} // namespace detail
} // namespace pybind11

TEST_SUBMODULE(class_custom_type_caster_mix, m) {
using namespace pybind11_tests::class_custom_type_caster_mix;

py::class_<NumberStore>(m, "NumberStore").def(py::init<int>()).def("Get", &NumberStore::Get);
}
9 changes: 9 additions & 0 deletions tests/test_class_custom_type_caster_mix.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
# -*- coding: utf-8 -*-
import pytest

from pybind11_tests import class_custom_type_caster_mix as m


def test_make_unique_pointee():
obj = m.NumberStore()
assert obj.Get() == 5 # custom type_caster wins.