Export C dll methods to c# P/Invoke - c

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.

Related

Should I use __stdcall on DLL export functions?

I'm writing a small DLL in C using mingw-w64, which should be callable by VB.net programs. The only exports are functions whose parameters and return types are primitive types.
Should I use __stdcall on the dllexport functions or not?
When searching the web I have seen examples both with and without it. There is discussion of how it affects name decoration but no advice as to whether this is a good thing or not, and what the impact is on my DLL's usability.
There is really no good reason to use nondefault calling convention/ABI (__stdcall or otherwise) anywhere except when you need to call an existing interface defined that way. It's just gratuitous ugliness. Where it's done all over existing Windows stuff, it's legacy cargo culting from the Win16 era, and has no actual rationale behind it.

Should a Fortran-compiled and C-compiled DLL be able to import interchangeably? (x86 target)

The premise: I'm writing a plug-in DLL which conforms to an industry standard interface / function signature. This will be used in at least two different software packages used internally at my company, both of which have some example skeleton code or empty shells of this particular interface. One vendor authors their example in C/C++, the other in Fortran.
Ideally I'd like to just have to write and maintain this library code in one language and not duplicate it (especially as I'm only just now getting some comfort level in various flavors of C, but haven't touched Fortran).
I've emailed off to both our vendors to see if there's anything specific their solvers need when they import this DLL, but this has made me curious at a more fundamental level. If I compile a DLL with an exposed method void foo(int bar) in both C and Fortran... by the time it's down to x86 machine instructions - does it make any difference in how that method is called by program "X"? I've gathered so far that if I were to do C++ I'd need the extern "C" bit to avoid "mangling" - there anything else I should be aware of?
It matters. The exported function must use a specific calling convention, there are several incompatible ones in common use in 32-bit code. The calling convention dictates where the function arguments are stored, in what order they are passed and how they are removed again. As well as how the function return value is passed back.
And the name of the function matters, exported function names are often decorated with extra characters. Which is what extern "C" is all about, it suppresses the name mangling that a C++ compiler uses to prevent overloaded functions from having the same exported name. So the name is one that the linker for a C compiler can recognize.
The way a C compiler makes function calls is pretty much the standard if you interop with code written in other languages. Any modern Fortran compiler will support declarations to make them compatible with a C program. And surely this is something that's already used by whatever software vendor you are working with that provides an add-on that was written in Fortran. And the other way around, as long as you provide functions that can be used by a C compiler then the Fortran programmer has a good chance at being able to call it.
Yes it has been discussed here many many times. Study answers and questions in this tag https://stackoverflow.com/questions/tagged/fortran-iso-c-binding .
The equivalent of extern "C" in fortran is bind(C). The equivalency of the datatypes is done using the intrinsic module iso_c_binding.
Also be sure to use the same calling conventions. If you do not specify anything manually, the default is usually the same for both. On Linux this is non-issue.
extern "C" is used in C++ code. So if you DLL is written in C++, you mustn't pass any C++ objects (classes).
If you stick with C types, you need to make sure the function passes parameters in a single way e.g. use C's default of _cdecl. Not sure what Fortran uses.

Where do i put the declarations of my DLL? + how to use it in onther language [C]

1) Lets say I create this DLL called MyDLL in c.
I have 2 files, 1 is MyDLL.c and the 2nd is MyDLL.h, than I compile the code
and get MyDLL.a and MyDLL.dll.
I know how i can use this dll in a new C project, I just include my MyDLL.h and give the
linker the path for my MyDLL.a
now lets say that I dont have the MyDLL.h, than i need to call LoadLibrary() but all the function's prototypes and all the typdefs MACROs and structs in the MyDLL.h, so how the program will know all this declarations?
or lets say I want to use the DLL in C# project or JAVA project? i cant include MyDLL.h..
2) If I have a function in the dll that get pointers as parametrs(void *, int * etc..), how can I send pointers as parameters if I dont have pointer in C# and JAVA or any other language?
Or if the function get struct for parameter? Or even a pointer to function?
Most languages you mention define their own foreign function interface (FFI) which is a mechanism for calling code written in other languages. FFI for Java is called JNI, and for C# - P/Invoke.

Override a C function defined in a static library

I have a static library of C files, compiled with g++ on Cygwin. I wish to unit test one function that is defined in the library. That function calls another function defined in that library and I wish to override the dependency to replace it with my own version of that function. I can't modify what's in the static library, so this solution [ Override a function call in C ] doesn't apply.
Usually, I can write a .cpp file and include the .c file containing the function I want to unit test, which essentially extends that file with the code I add. It's a dirty trick I'd never use for production code but it's handy for unit testing C files, because it gives my test code access to static things in that C file. Then, I can write in my fake version of the dependency, and my unit test function that calls the function I'm testing. I compile my.cpp to get my.o, then link it with the static library. In theory, since the linker has found a definition for the dependency already (the one I provide) it won't look in the library and there will be no conflict. Usually this works, but now I'm getting a "multiple definition" error where the linker first finds my fake and then finds the real one. I don't know what might cause this and don't know what to look for. I also can't boil this down to a simple example because my simple examples don't have this problem.
Ideas please?
One possibility (admittedly, and ugly one, but...) is to extract the individual object files from the static library. If the function you're calling and the function it's calling are in separate object files, you can link against the object file containing the function you need to call, but not against the one containing the function it calls.
This only gives you granularity on the level of complete object files though, so if the two functions involved are both in the same object file, it won't work. If you really need to get things to work, and don't mind making a really minor modification to the object file in question, you may be able to use a binary editor to mark the second function as a weak external, which means it'll be used in the absence of any other external with the same name, but if another is provided, that will be used instead.
Whether that latter qualifies as "modifying the library" or not depends a bit on your viewpoint. It's not modifying the code in the library, but is modifying a bit of the object file wrapper around that code. My guess is that you'd rather not do it, but it may still be the cleanest way out of an otherwise untenable situation.
It turns out the reason the linker found both defintions of the function is that the faked function's source file defined a variable which is extern'ed in its header file. That unresolved external in the header file caused the linker to link the faked function's object file (the whole thing) to the tested function's file inside the library. So, it's impossible to extract the definition of the tested function without the definition for the dependency.
What I ended up doing was similar to Override a function call in C where I used a different function name instead of the same one, and a preprocessor directive to swap the two. I put the preprocessor directive and the fake function in a separate file which can be included in a unit test, so the production code in the library does not have to be touched. Plus, if I want to fake that same function for another unit test somewhere else, I can re-use the new file.
Depending on your platform and performance requirements, you might be able to use pin to dynamically modify the application and replace one function with another at runtime.
There's no direct example in the manual, but you could easily modify one of the sample pin tools to do this.

Inversion of Control or Dependency Injection -- anyone doing it in 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.

Resources