Skip to content

Commit 556c00d

Browse files
Vipul-Cariappaguitargeek
authored andcommitted
[cppyy] Handle polymorphic types when converting from class fields
fixes #16062
1 parent 8b8789b commit 556c00d

File tree

2 files changed

+38
-2
lines changed

2 files changed

+38
-2
lines changed

bindings/pyroot/cppyy/CPyCppyy/src/Converters.cxx

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2183,9 +2183,10 @@ template <bool ISCONST>
21832183
PyObject* CPyCppyy::InstancePtrConverter<ISCONST>::FromMemory(void* address)
21842184
{
21852185
// construct python object from C++ instance read at <address>
2186+
Cppyy::TCppScope_t actual_class = Cppyy::GetActualClass(fClass, *(void**)address);
21862187
if (ISCONST)
2187-
return BindCppObject(*(void**)address, fClass); // by pointer value
2188-
return BindCppObject(address, fClass, CPPInstance::kIsReference); // modifiable
2188+
return BindCppObject(*(void**)address, actual_class); // by pointer value
2189+
return BindCppObject(address, actual_class, CPPInstance::kIsReference); // modifiable
21892190
}
21902191

21912192
//----------------------------------------------------------------------------

bindings/pyroot/cppyy/cppyy/test/test_datatypes.py

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2370,3 +2370,38 @@ def test50_int8_uint8_global_arrays(self):
23702370

23712371
assert [ns.test[i] for i in range(6)] == [-0x12, -0x34, -0x56, -0x78, 0x0, 0x0]
23722372
assert [ns.utest[i] for i in range(6)] == [ 0x12, 0x34, 0x56, 0x78, 0x0, 0x0]
2373+
2374+
def test51_polymorphic_types_in_maps(self):
2375+
"""Auto down-cast polymorphic types in maps"""
2376+
import cppyy
2377+
from cppyy import gbl
2378+
2379+
cppyy.cppdef(
2380+
"""
2381+
namespace PolymorphicMaps {
2382+
struct Base {
2383+
int x;
2384+
Base(int x) : x(x) {}
2385+
virtual ~Base() {}
2386+
} b(1);
2387+
2388+
struct Derived : public Base {
2389+
int y;
2390+
Derived(int i) : Base(i), y(i) {}
2391+
} d(1);
2392+
2393+
std::map<int, Base*> getBaseMap() {
2394+
std::map<int, Base*> m;
2395+
m[1] = &b;
2396+
m[2] = &d;
2397+
return m;
2398+
}
2399+
} // namespace PolymorphicMaps
2400+
"""
2401+
)
2402+
2403+
for k, v in gbl.PolymorphicMaps.getBaseMap():
2404+
if k == 1:
2405+
assert type(v) == gbl.PolymorphicMaps.Base
2406+
else:
2407+
assert type(v) == gbl.PolymorphicMaps.Derived

0 commit comments

Comments
 (0)