Skip to content

Added a client context parameter to the modbus_t context, and getter/setter methods.#646

Open
JetForMe wants to merge 7 commits intostephane:masterfrom
latencyzero:rmann/add-context
Open

Added a client context parameter to the modbus_t context, and getter/setter methods.#646
JetForMe wants to merge 7 commits intostephane:masterfrom
latencyzero:rmann/add-context

Conversation

@JetForMe
Copy link
Contributor

@JetForMe JetForMe commented Jul 13, 2022

This commit adds

  • client_context to the _modbus struct
  • modbus_set_client_context()
  • modbus_get_client_context()
  • Documentation for the above

The code otherwise ignores _modbus.client_context. It is available to calling code for it to associate its own context with the callback (typically a pointer to an object).

@cla-bot cla-bot bot added the cla-signed label Jul 13, 2022
@stephane
Copy link
Owner

I'm reluctant to add any new field to _modbus struct (even more a free pointer not managed).
Could you explain your use case?

@JetForMe
Copy link
Contributor Author

Note that libmodbus will never do anything to that field, except pass it back in the callback. It does not own the contents of that field.

A common scenario in object-oriented languages like C++ or Swift is to wrap library data structures. In this case, I've defined a class MODBUSContext that has a pointer to modbust_t. When the library provides any kind of callback functionality, there needs to be a way for the called function to get at its own context. In my case, my class implements the custom RTS functionality, but to do so, it needs its own context. The only way to get at that context when called back by libmodbus is for libmodbus to keep track of it. I cast a pointer to my object to void*, and when my callback is called, I get that pointer out of the modbus_t struct, cast it back to my class type, and I'm off to the races.

This is a very common and widely-used pattern.

@JetForMe
Copy link
Contributor Author

@stephane Does that make sense?

@JetForMe
Copy link
Contributor Author

I've added documentation for the new functions.

@Biblbrox
Copy link

Hi stephane and JetForMe. Are there any plans to merge that code with master? I haven't found the code from the pull request in the master branch. I have the same issue and the solution provided by JetForMe seems to be reasonable.

@LianYangCn
Copy link

I'm reluctant to add any new field to _modbus struct (even more a free pointer not managed). Could you explain your use case?

When I use libgpiod to read/write the custom RTS IO, I need to at least keep track of the chip obtained from gpiod_chip_open, so that I can accurately use this chip in the callback to get the line, and finally perform the IO operation using gpiod_line_set_value.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants