Removing duplication between similar functions in C and C++, in an EmPy template

112 Views Asked by At

Those @things are EmPy

C++

  const char *
  publish__@(spec.base_type.type)(void * untyped_data_writer, const void * untyped_message)
  {
    DataWriter * topic_writer = static_cast<DataWriter *>(untyped_data_writer);
    const __ros_msg_type & ros_message = *(const __ros_msg_type *)untyped_message;
    __dds_msg_type dds_message;
    conversion_cpp(ros_message, dds_message);

    @(__dds_msg_type_prefix)DataWriter * data_writer =
      @(__dds_msg_type_prefix)DataWriter::_narrow(topic_writer);
    DDS::ReturnCode_t status = data_writer->write(dds_message, DDS::HANDLE_NIL);

    // some common switch statements in C and C++

    }
  }

C

static const char *
publish(void * data_writer, const void * cool_message)
{
  if (!data_writer) {return "data writer handle is null";}
  if (!cool_message) {return "ros message handle is null";}

  DDS::DataWriter * topic_writer = static_cast<DDS::DataWriter *>(data_writer);
  __dds_msg_type dds_message;
  const char * err_msg = conversion_c(cool_message, &dds_message);
  if (err_msg != 0) {return err_msg;}

  @(__dds_msg_type_prefix)DataWriter * data_writer =
    @(__dds_msg_type_prefix)DataWriter::_narrow(topic_writer);
  DDS::ReturnCode_t status = data_writer->write(dds_message, DDS::HANDLE_NIL);
@[for field in spec.fields]@
@[if field.type.type == 'string']@
@[if field.type.is_array]@
  {
@[if field.type.array_size]@
    size_t size = @(field.type.array_size);
@[else]@
    size_t size = dds_message.@(field.name)_.length();
@[end if]@
    for (DDS::ULong i = 0; i < size; ++i) {
      // This causes the DDS::String_mgr to release the given c string without freeing it.
      dds_message.@(field.name)_[i]._retn();
    }
  }
@[else]@
  // This causes the DDS::String_mgr to release the given c string without freeing it.
  dds_message.@(field.name)_._retn();
@[end if]@
@[end if]@
@[end for]@

  // some common switch statements in C and C++
  }
}

This question is a bit specific to an open source project I am trying to contribute to, so I ll point to the exact functions I guess. This is the original C method and this is the C++ method

Do I need to use function pointers?
Another thing going on here is that the C package depends on the C++ package.

(Maybe this isn't good question or is a vague question, but I am not sure what to do as I am new to this codebase)

0

There are 0 best solutions below