user506901
user506901

Reputation: 699

Facilitate the use of C++ within an existing C implementation

Recently I was assigned a task to provide a C implementation of my C++ code. Since the original code is large, and is largely relying on structures not present in C, I wonder what would be the easiest way for the transfer.

I read that there are wrappers that allow one to use C++ in C? Will these allow me to simply copy/paste the code in C?

Also, I explored the following http://attractivechaos.wordpress.com/2008/09/19/c-array-vs-c-vector/

Do you have a suggestion on how I might do the task without much work (clearly, because the code is already written, needs only be "transferred")?

Upvotes: 2

Views: 310

Answers (3)

thiton
thiton

Reputation: 36059

This task depends heavily on your boundary conditions. The other posters defined a good method to provide a C interface to a C++ module.

If you absolutely need to convert your code to pure C, but maintainability is not an issue, you might think about compiling your code and then using a C decompiler to generate gibberish that compiles as valid C code into a C module functionally equivalent to your C++ module.

Upvotes: 0

Some programmer dude
Some programmer dude

Reputation: 409472

You can write a wrapper-library that uses internal handles to the objects and classes used, then. A function to call a method in an object might look like this:

extern "C" int classname_methodname(int handle, int param1);

The handle parameter can then be an index into a vector<classname> internal_classname.

The actual function, classname_methodname in my example above, just fetches the object from the vector and calls the method in the object with its paremeters.

To create an object instance, you can have a classname_create or similar named function, that creates a new instance and then returns the handle used for the other functions.

Upvotes: 1

Andy Thomas
Andy Thomas

Reputation: 86509

You can wrap C++ code in a C API.

However, it may still depend on the C++ library. If your requirements prevent use of the C++ library, then wrapping the existing code in a C API is not going to help you.

Upvotes: 1

Related Questions