How to use c library in c
How to use c library in c
wrap a c++ library in c? (don’t «extern c»)
is it possible to wrap a c++ library into c?
how could i do this?
are there any existing tools?
(need to get access to a existing c++ library but only with C)
5 Answers 5
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
You can write object-oriented code in C, so if it’s an object-oriented C++ library, it’s possible to wrap it in a C interface. However, doing so can be very tedious, especially if you need to support inheritance, virtual functions and such stuff.
If the C++ library employs Generic Programming (templates), it might get really hairy (you’d need to provide all needed instances of a template) and quickly approaches the point where it’s just not worth doing it.
Assuming it’s OO, here’s a basic sketch of how you can do OO in C:
Depending on your requirements, you could amend that. For example, if this is going to be a public C interface to a private C++ API, handing out real pointers as handles might make it vulnerable. In that case you would hand out handles that are, essentially, integers, store the pointers in a handle-to-pointer map, and replace the cast by a lookup.
Having functions returning strings and other dynamically sized resources can also become quite elaborate. You would need the C caller provide the buffer, but it can’t know the size before-hand. Some APIs (like parts of the WIn32 API) then allow the caller to call such a function with a buffer of the length 0, in which case they return the length of the buffer required. Doing so, however, can make calling through the API horribly inefficient. (If you only know the length of the required buffer after the algorithm executed, it needs to be executed twice.)
One thing I’ve done in the past is to hand out handles (similar to the handle in the above code) to internally stored strings and provide an API to ask for the required buffer size, retrieve the string providing the buffer, and destroy the handle (which deletes the internally stored string).
That’s a real PITA to use, but such is C.
How to use Libraries
For some reason I’m never able to use external libraries in any language. I’m looking for instructions/explanations of how to use external libraries, as well as how they work. When I search online, I get fragments that never seem to apply to whatever library I download and try and use. I work on both a mac and a pc, and C++ examples are fine. I use eclipse IDE with the C++ plug in. If there are instructions that apply to all libraries that would be great.
3 Answers 3
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
Say you have a class Unuseful defined as follows:
Now, you have another class that needs printing unuseful statements:
This means that you want to use an external library containing the specific implementation ( printUnusefulStatement ) that you want to include in your code.
You may use this library in two ways:
Case 1: using a library at compile time
This is the simplest case. You have the source code of the library you have to use and you simply have to compile it together with your existing code (say main.cpp file). Typically you are the author and user of the library (a class that accomplishes a task you need).
Compiling with this command:
allows you to use the implementation you need in your main.cpp file.
Case 2: linking a library
Static libraries are created by simply archiving the *.o files with the ar program:
Let’s suppose now you have the Unuseful.h file and the shared library ( libunuseful.so file) and you have a main.cpp file that instantiates a Unuseful object and calls the printUnusefulStatement method.
If you try to compile this file ( g++ main.cpp ) the linker will complain because it cannot find the printUnusefulStatement symbol.
It’s time to use the library:
Since the shared library is loaded at run-time, the execution of the a.out executable may fail because the system is not able to find the library. Typically this can be solved by appropriately setting an environment variable indicating which paths to use to search for dynamic libraries:
Done, now your executable has been compiled and it will be able to run and load the library it needs.
Conclusion
This is a rapid overview on libraries which I hope can help you understand how they are used and provided to others.
There are many many aspects that should be investigated in more detail, if you are interested: g++ options when creating shared libraries, ar options, environment variables, the shared libraries format and so on.
[*]: In a Unix environment
[**]: If supported for the target machine, emit position-independent code, suitable for dynamic linking and avoiding any limit on the size of the global offset table. This option makes a difference on the m68k, PowerPC and SPARC. Position-independent code requires special support, and therefore works only on certain machines. [From the g++ man page]
Tips for using a C library from C#
I’ve got a library in C which I’d like to use from C#.
From what I’ve gleaned off the internet, one idea is to wrap it in a C++ dll, and DllImport that.
Given an interface like this, what are the nasties I should be looking out for? (And solutions too, please)
— Rewrite in C#? I started, but it’s already machine-translated from FORTRAN, and I don’t much like coding stuff I can’t understand.
— Recompile in C++? I’m thinking about it, but it looks like a lot of pain
6 Answers 6
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
For the record, I got most of the way to getting this working, then ended up pulling the appropriate C files into the C++ project (because I was fighting with compatibility issues in code that I didn’t even need).
Here are some tips I picked up along the way which may be helpful for people happening on this question:
Marshalling arrays
Calling convention
Packaging the callback
Obvious, but it wasn’t immediately obvious to me:
.def file
Any functions you want to expose from C++ project (to be DllImport ed), need to figure in the ModDef.def file, who’s contents would look something like this:
extern «C»
Precompiled headers
Tutorial: HowTo integrate a C++ library/class into a C programm
Emagine the situation: You have written a program in C and now you have the requirement to integrate an existing third parity C++ library into your program.
The C++ Library
The only thing you have is the class definition in the header file of the library:
It is a simple class with only one member variable m_i and one setter and one getter method.
Perhaps you don’t have the source code of the library, perhaps you only have a compiled version. To be able to reproduce the example here is the source of the class:
To compile the class with GNU C++ comiler simply type:
This gives you the object file that can be linked into your programm. In this place I won’t explain how to create a complete library.
The C++ way
Just for comparison here a simple C++ program that uses our new class:
This program can be compiled with:
And linked with:
Start the C++ program with:
The Problem
If we want to access a C++ library from C code we have two problems that we have to solve:
The C-Wrapper
To solve these problems we have to write a C-wrapper around our C++ class. Our wrapper header file will be readable by the C and the C++ compiler.
The extern «C» <> statement tells the C++ compiler to use the C style name mangling so a C compiler will find the correct symbols in the object file later. The #ifdef __cplusplus contition is because the C compiler does not know the keyword extern.
For the C compiler we define a dummy class handler with typedef struct MyClass MyClass.
And then the constructor, method and destructor wrappers.
The following file is the wrapper code, written in C++, but with one important thing: it is defined as extern «C»!
To compile the wrapper with GNU C++ comiler simply type:
The C Program
Now we are ready to use the C++ class in our C code:
This program can be compiled with the C compiler:
Note that the linking has to be done with the C++ comiler, a C linker like ldd does not work:
Start the C program with:
You should now get the same result as with your C++ program above.
How to call C++ function from C?
Calling C function from C++:
If my application was in C++ and I had to call functions from a library written in C. Then I would have used
This wouldn’t mangle the name C_library_function and linker would find the same name in its input *.lib files and problem is solved.
Calling C++ function from C.
But here I’m extending a large application which is written in C and I need to use a library which is written in C++. Name mangling of C++ is causing trouble here. Linker is complaining about the unresolved symbols. Well I cannot use C++ compiler over my C project because thats breaking lot of other stuff. What is the way out?
By the way I’m using MSVC
7 Answers 7
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
You need to create a C API for exposing the functionality of your C++ code. Basically, you will need to write C++ code that is declared extern «C» and that has a pure C API (not using classes, for example) that wraps the C++ library. Then you use the pure C wrapper library that you’ve created.
Your C API can optionally follow an object-oriented style, even though C is not object-oriented. Ex:
I would do it in the following way:
(If working with MSVC, ignore the GCC compilation commands)
Suppose that I have a C++ class named AAA, defined in files aaa.h, aaa.cpp, and that the class AAA has a method named sayHi(const char *name), that I want to enable for C code.
Compiling this class as regularly done for C++. This code «does not know» that it is going to be used by C code. Using the command:
Now, also in C++, creating a C connector:
Defining it in files aaa_c_connector.h, aaa_c_connector.cpp. This connector is going to define a C function, named AAA_sayHi(cosnt char *name), that will use an instance of AAA and will call its method:
Compiling it, again, using a regular C++ compilation command:
Now I have a shared library (libaaa_c_connector.so), that implements the C function AAA_sayHi(const char *name). I can now create a C main file and compile it all together:
Compiling it using a C compilation command: