Mohsen
Mohsen

Reputation: 21

Isolate C library like class (C++ code)

I use a library to control a device. This Library is written in C language. This library has a global variable to keep the device ID (port number). This library provide a function to determine the which port we use.

initialize(int deviceIndex, int baudrate)

This function change the global variable. All other function use this global variable.

I can control one device with this library; however, I want control two devices at same time.

If I use this function, two times, the global variable changed and I lost one device.

I write my code in C++. I want to know if there is any way to use this library twice, Like a class that we create several object and even public variables of each class are independent.

Edit:

  1. There are platform dependent ways. What platform are you on?

I should write code in both Visual C++ (Windows) and Qt C++ (Linux Kubuntu)

  1. Can you change the source code of that library?

Yes, I can but it is about 2000 lines and 4 files (two .c and two .h)

Upvotes: 2

Views: 746

Answers (2)

Maxim Egorushkin
Maxim Egorushkin

Reputation: 136286

I want to know if there is any way to use this library twice.

You can only have one instance of the library and its symbols (global functions and variables) (regardless whether it is a static or a shared library) in one process. If you need more than one, then spawn more processes.

You can wrap this functionality in a class, so that when you create an object of that class it automatically spawns a worker sub-process for you and its member functions communicate with that particular sub-process using some form of IPC (e.g. pipes, socket pair, shared memory, files, etc..).

Upvotes: 4

shrike
shrike

Reputation: 4511

The global variable owning the device id may not be the single problem you'll have to face when trying to use this library for more than 1 device. The library may define a bunch of other global or static variables.

Worse, the underlying I/Os the library performs to communicate with the device may not be compatible with more than one device at the same time. So, the first test you should make before all is to run the library as is in two different executables and check if each process can work with a different device at the same time.

If this works, great, you can go for the solution suggested by Maxim or try to wrap your library into one or more classes. For the latter, make sure to locate all global and static variables in the code (this should not be too hard) and make them members of the class(es).

Upvotes: 1

Related Questions