diff --git a/ruby/ext/google/protobuf_c/encode_decode.c b/ruby/ext/google/protobuf_c/encode_decode.c index 12080d034a750..9fa4bfd95a91a 100644 --- a/ruby/ext/google/protobuf_c/encode_decode.c +++ b/ruby/ext/google/protobuf_c/encode_decode.c @@ -1106,6 +1106,13 @@ static void putmsg(VALUE msg_rb, const Descriptor* desc, TypedData_Get_Struct(msg_rb, MessageHeader, &Message_type, msg); + if (desc != msg->descriptor) { + rb_raise(rb_eArgError, + "The type of given msg is '%s', expect '%s'.", + upb_msgdef_fullname(msg->descriptor->msgdef), + upb_msgdef_fullname(desc->msgdef)); + } + for (upb_msg_field_begin(&i, desc->msgdef); !upb_msg_field_done(&i); upb_msg_field_next(&i)) { diff --git a/ruby/tests/encode_decode_test.rb b/ruby/tests/encode_decode_test.rb index 2bd9b98b5a9a4..f8b991cdb8240 100644 --- a/ruby/tests/encode_decode_test.rb +++ b/ruby/tests/encode_decode_test.rb @@ -84,4 +84,14 @@ def test_encode_json assert_match 'optional_int32', json end + + def test_encode_wrong_msg + e = assert_raise ::ArgumentError do + m = A::B::C::TestMessage.new( + :optional_int32 => 1, + ) + Google::Protobuf::Any.encode(m) + end + end + end