Inversion of Control or Dependency Injection -- anyone doing it in C? - c

See, for example, here
https://stackoverflow.com/questions/139299/difference-between-dependency-injection-di-inversion-of-control-ioc
to remind yourself what IoC and DI are.
The question and answer here
Is Inversion of Control specific to OO languages?
suggests that it does not require an OO language.
Now, my question: Anyone doing this in C?
I am asking because we write embedded C and are considering applying these methods, without changing our programming language.

Doing it in C all the time. The hint is given in the answer from Azder in your second link:
"When you give a Windows API function a pointer to a callback function, you give them the control of calling your function with their own parameters."
From this point of view, the concept is already used in the Standard library for the functions qsort() and bsearch().

On windows, you have COM which does something similar. You have an interface and provide an implementation in a DLL. You register the DLL and that process of registration makes an entry in the registry mapping the interface (UUID) and the DLL which provides the implementation. Based on this information, when you execute QueryInterface(), the COM service will load the corresponding DLL and create an instance of the implementation object, typecast it to the requested interface type and return.
This is IoC using COM. Since COM is implemented in 'C', I am sure it is just working out the details to get this working on your embedded system. Instead of registry, you will need a file to store that mapping between interface, implementation and DLL. This is done in Catia (from Dassault Systemes) in their CNext (V5/V6) architecture. It is called the Object modeler framework.
Steps to achieve this:
Define a naming convention for function that returns a pointer to an interface
Create a file with interface and DLL in which it is implemented
Implement the interface in a DLL and update the file in #2
In the main code, read the file and create a map of interface and DLL
When you need an interface, load the DLL if not loaded and get the address of the function that returns the pointer to interface (based on defined naming convention)
Ex: For IDoSomething interface, your function might be Get_IDoSomething().
Since we get the address of function based on name, it is done at runtime and not at compile time.
Invoke the function at the address you get from #5. You now have a pointer to the interface based on the implementation in DLL as specified in #3
You therefore tie the interface to its implementation at runtime.

Related

Why aren't binaries of different languages compatible with each other? How do you make them compatible?

A swift app, will convert its dynamic frameworks into binaries. And once something is a binary, then it's no longer Swift/Ruby/Python, etc. It's machine code.
Same thing happens for a Python binary. So why aren't the machine codes compatible with each other out of the box?
Is it just that a simple mapping is required to bridge one language to the other?
Like if I needed to use a binary created from the Swift language — into a Python based app, then do I need to expose the Swift Headers to Python for it to work? Or something else is required?
I assume you're talking about making calls in one language to a library compiled in a different language.
At the assembly language level, there are standards (ABI, for Application Binary Interface) that define how function parameters are passed in registers, how values are returned, the behavior of the stack, etc. ABIs are architecture and operating-system-dependent. Usually any function that is exported in a library will follow the ABI.
It is plain that ABIs basically expect a C language model for functions: a single return value, a well-defined data type for each function parameter as well as the return value, the possibility of using pointers, etc.
Problems start to arise once you move to a higher level language. C++ already introduces complications: whereas the name of a C function is the same in assembly (often a _ character is prepended), in C++ function names must encode data types due to the possibility of overloaded functions with the same name but different parameters. Thus, names must be mangled and demangled -- this is why a prototype for a C function must be declared as extern "C" in C++. Then there are issues of the classes (this pointer, vtables), namespaces and so on, which complicate matters further.
Then you have dynamically typed languages like Python. In truth, there is no such thing as dynamic typing at the assembly language levels: the instruction encodings in machine language (i.e. binary codes as they're read by the CPU when executed) implicitly determine whether you're using an integer or floating-point or SIMD instruction (and the width of operands), which also determines which of the different register banks are accessed. Although the language makes dynamic typing transparent to you, at the assembly code level, the interpreter/JIT/compiler must resolve them somehow, because ultimately the CPU must be told exactly what data type to operate on.
This is why you can't directly call a C function (or in general any library function) from Python -- unlike a pure Python function which can disregard the types of its parameters, library functions must know the exact types of each parameter and the return type. Thus, you must use something like ctypes for Python, explicitly specifying the types in question for each function that needs to be called -- in a way, this is similar to function prototypes usually found in C headers. It is possible to write functions in C that are directly callable from Python (and, in that case, essentially from Python alone), but you'll have to jump through a few hoops.
As for the particular language pairing you're interested in (Python/Swift), a cursory search came up with this thread in the Swift forums (this one, linked from there, may also be interesting. Reading the thread, there appears to be two feasible solutions at this time: first, use the #_cdecl attribute (which isn't officially supported) to make a C function, and then call it from Python using ctypes. But the second and apparently more promising one is to use the #objc attribute in Swift, and use PyObjC in Python. I assume this will allow using some of the higher-level features of Swift, at least those that intersect with what Objective-C offers.

Multiple calls to a dll from Dymola

I am implementing a model that requires to call a dll library twice, in order to receive from it specific values
the first call is to set up a system inside the library (for example, a powertrain from a catalogue of components and some design parameters)
the second call is to retrieve the performance of a component from such system (let's say the efficiency of a specific electric machine when used in that powertrain)
These two calls to the dll go together, and may be repeated during simulation time.
So far, I've only managed to interface my model to the dll through separate calls from Modelica external functions (one for the first call, one for the second). However, the state of the system is reset between the first and the second call.
Is there a way in Modelica to load a dll, call the same instance of
it multiple times, and eventually close it when the job is done?
Perhaps is it only possible to achieve such feature by bundling the
whole functionality in an external function?
Or am I attempting something that just doesn't work, because of some
technical aspects that I am not aware of? (I don't know, perhaps the
way it all gets compiled during translation)
If I understand this correctly, it looks like your external DLL has some kind of object pointer that is returned when you instantiate it, and this needs to be passed in at every subsequent function call to other functions in the DLL (to preserve the state).
So to do this in Modelica, you need to create an external object class. These are used to preserve state externally and has constructors and destructors to manage its memory. You can write small wrapper C functions to interface with your DLL functions that you can directly include in Modelica annotations, or write a wrapper lib.
Documentation
https://build.openmodelica.org/Documentation/ModelicaReference.Classes.ExternalObject.html
Simple Example
https://www.claytex.com/tech-blog/external-object-example-detecting-initial-rising-edge/
Detailed Example
https://github.com/modelica-3rdparty/ExternData/releases

Export C dll methods to c# P/Invoke

How to view method names with parameters list for a c dll?
I am trying to write C# wrapper for some C dlls from a third party application but on viewing c dll in dependency walker or PE explorer it just shows method names with some #### symbols.
To write a dllImport wrapper I must know method name and parameters list but I do not have any idea how can view the method names and parameters.
Realistically you need the documentation for the library. Without that you are going to struggle. Even if you can divine the function prototypes (parameters, calling convention etc.) you will struggle to know how to call those functions. For instance suppose you have this function:
void foo(int, int*);
Is the second parameter a pointer to a single value, or an array? You cannot tell from just the prototype.
Furthermore, the DLL will likely require constants, structs, and so on, none of which have meta-data in the DLL.
You can likely retrieve the prototypes with a demangler, i.e. http://demangler.com/ but realistically that won't be enough. Contact the vendor to obtain the documentation.

Header Files in C-language and Reusability of Object Oriented Programming?

In interview I was ask that as re-usability is one of the main advantages of Object Oriented Programming but it can also be achieved by include header files in C language? So what is the difference in OOP re-usability and C Header files?
If by "re-usability" you are simply implying that code does not need to be repeated in each code module, then yes, a header-file in C accomplishes that task because it allows the declarations for functions and variables defined with external linking in one code module to be used in another code module without the user having to re-type all those declarations and/or attempt to place every definition of every function that would normally be part of a library into each code module. Thus the duplication of code is prevented.
Object-oriented programming through the use of inheritance and polymorphism in languages like C++ and Java have a similar effect ... you define an interface and/or a base-class once, and then you are able to "include" that code via inheritance in another class. Additionally, virtual methods along with polymorphism allows you to write functions that take a single base-class type as an argument, yet call code that is actually defined in a derived class-type. This essentially means you can call new code (i.e., your derived class), in old code (i.e., the function that accepted a base-class type). For instance, as a library developer, you could define a set of base-class types/interfaces, and a user could derived from those base-classes, yet still use them effectively in the same functions that were included with the library that accept arguments of the base-class type. Thus you are not forced to reduplicate those functions ... they are still usable by your "new" derived classes.
Basically, without OOP and just using included headers, you can use an existing function without needing to write it again yourself.
However, if you intend to use a very similar, but slightly different function, you have no choice but to write it yourself. You can not reuse the original function in this case, you have to write a new one.
Advantage of OOP: If that function were a class instead, you can inherit from it, and only add a few small methods, so you can reuse most of the methods of the original class.
It is important here not to confuse language support for OOP and OOP itself. The common practice for re-usable C code is to define data types and functions operating on the data types in an header file, and then implement functions in terms of these data types and functions. When you look at it closely, this is an implementation of OOP, even though without proper language support and thus less stable. But: A C header file that typedefs data structures and functions operating on these data structures is an implementation of OOP.
Therefore, there is no difference in code reusability, it is just a view on two different layers. OOP is about a paradigm, C headers about an implementation in the C context.

How one can achieve late binding in C language?

How one can achieve late binding in C language ?
Late binding is not really a function of the C language itself, more something that your execution environment provides for you.
Many systems will provide deferred binding as a feature of the linker/loader and you can also use explicit calls such as dlopen (to open a shared library) and dlsym (to get the address of a symbol within that library so you can access it or call it).
The only semi-portable way of getting late binding with the C standard would be to use some trickery with system() and even that is at least partially implementation-specific.
If you're not so much talking about deferred binding but instead polymorphism, you can achieve that effect with function pointers. Basically, you create a struct which has all the data for a type along with function pointers for locating the methods for that type. Then, in the "constructor" (typically an init() function), you set the function pointers to the relevant functions for that type.
You still need to include all the code even if you don't use it but it is possible to get polymorphism that way.
Symbol binding in C is always done at compile time, never runtime.
Library binding, or dynamic linking as it's called, is done via dlopen() and dlsym() on *nix, and LoadLibrary() and GetProcAddress() on Windows.
How one can achieve late binding in C language ?
The closest would be through dynamic loading of library (DLL) such as with dlopen & dlsym on Linux. Otherwise, it is not directly available in C.
Use Objective-C or Lua. Both are late-bound languages which can easily interface with C.
Of course you could implement your own name resolution scheme, but why re-invent the wheel?
Unfortunately you did not specify an OS. For Unix you can use shared libraries, or create a configurable (plugin) module structure. For details you may find the source code of an apache 1.3 webserver useful. http://httpd.apache.org/download.cgi
cppdev seems to be the one and only to hit the spot with his/her remark.
Please, have a look at the definition itself. In a few words:
Late binding, or dynamic binding, is a computer programming mechanism
in which the method being called upon an object is looked up by name
at runtime.
All other answers just miss the main point, that is "look up by name".
The needed solution would be very similar to a lookup table of pointers to functions along with a function or two to select the right one by name (or even by signature). We call it a "hash table".

Resources