1

I am having compile issues with libmodbus. I have the following code

boost::shared_ptr <modbus_t> ctx;
ctx->modbus_new_tcp(ip_address.c_str(), modbus_port);

but I get the following error

error: invalid use of incomplete type 'struct _modbus'

it points to this line in modbus.h

typedef struct _modbus modbus_t;

I do not understand enough about this to troubleshoot my problem. What do you think it is? Is this library not comptatible with a smart pointer? They tell you to use a regular pointer

modbus_t* ctx;

Thank you.

xinthose
  • 3,213
  • 3
  • 40
  • 59

2 Answers2

3

You could - perhaps - use a

if (std::unique_ptr<modbus_t, void(*)(modbus_t*)> mb(modbus_new_tcp(ip_address.c_str(), modbus_port), &modbus_free)) {

    modbus_connect(mb);

    /* Read 5 registers from the address 0 */
    modbus_read_registers(mb, 0, 5, tab_reg);

    modbus_close(mb);
} // modbus_free invoked, even in the case of exception.

This, of course, assuming that there is unique ownership.

sehe
  • 374,641
  • 47
  • 450
  • 633
2

In fact this appears to be a C-style API where they've completely hidden the implementation of modbus_t from you as a user (since you pass the pointer to free functions rather than calling object members).

What this means is that you can't use shared_ptr out of the box (since it needs the definition to call delete, which also happens to be the wrong call to make). There may be a way to use a custom deleter that calls the appropriate cleanup function (probably modbus_free). You would then have to use .get() to get the raw pointer any time you wanted to call into the API.

Mark B
  • 95,107
  • 10
  • 109
  • 188