Declaring multiple instances of a c++ class which uses C code - c++

I have some C libraries which I would love to be able to be able to wrap in a c++ class and create multiple, completely separate instances of. I tried doing this but the problem is that the variables in the C code are simply shared among all c++ class instances.
I've tried making a static library and referencing that but to no avail. Does anyone know how one can do this?
Code example below: I have a C file called CCodeTest which simply adds some numbers to some variables in memory. I have a class in MathFuncsLib.cpp, which uses this. I want to be able to create multiple instances of the MyMathFuncs class and have the variables in the C code be independent
CCodeTest.h
#ifndef C_CODE_TEST_H
#define C_CODE_TEST_H
extern int aiExternIntArray[3];
#if defined(__cplusplus)
extern "C" {
#endif
#define CCODE_COUNT 3
void CCodeTest_AddToIntArray(int iIndex_);
int CCodeTest_GetInternInt(int iIndex_);
int CCodeTest_GetExternInt(int iIndex_);
#if defined(__cplusplus)
}
#endif
#endif //defined(C_CODE_TEST_H)
MathFuncsLib.cpp
#include "MathFuncsLib.h"
#include "CCodeTest.h"
using namespace std;
namespace MathFuncs
{
void MyMathFuncs::Add(int iNum_)
{
CCodeTest_AddToIntArray(iNum_);
}
void MyMathFuncs::Print(void)
{
for(int i = 0; i < CCODE_COUNT; i++)
{
printf("Intern Index %i: %i\n", i, CCodeTest_GetInternInt(i));
printf("Extern Index %i: %i\n", i, CCodeTest_GetExternInt(i));
}
}
}
Any help would be much appreciated!

You have a global variable called aiExternIntArray. That is the problem. Each instance of your C++ class operates on that array.
What you need to do is create a struct that holds an int[3] so that you can create separate instances of this type.
typedef struct
{
int aiIntArray[3];
} CodeTestStruct;
void CCodeTest_AddToIntArray(CodeTestStruct* ct, int iIndex_);
int CCodeTest_GetInternInt(CodeTestStruct* ct, int iIndex_);
int CCodeTest_GetExternInt(CodeTestStruct* ct, int iIndex_);
In C++, your class should encapsulate the CodeTestStruct.
class CodeTestClass
{
public:
void AddToIntArray(int iIndex_)
{
CCodeTest_AddToIntArray(&m_ct, iIndex_);
}
int GetInternInt(int iIndex_)
{
CCodeTest_GetInternInt(&m_ct, iIndex_);
}
int GetExternInt(int iIndex_)
{
CCodeTest_GetExternInt(&m_ct, iIndex_);
}
private:
CodeTestStruct m_ct;
};

Thank you for the answers - the suggestions above are all very valid.
My problem is an uncommon one as the C code I'm trying to run will be on an embedded system with very limited resources and so I am trying to minimize pointer dereferencing and state management etc...
I am using this C code in a computer exe to simulate multiple microprocessors running this code in parallel. So I've decided to create two DLLs that both share the same C source but have slightly different interfaces so that the C code, when loaded by importing the DLLs will be in a separate memory space and allow me to simulate multiple micros in one execution stream.

This is why you should never use global variables. That includes euphemisms for global variables like "singletons". There are exceptions to this rule, but they almost all involve systems-level programming and are not applicable to applications or (non-system-level) libraries.
To solve the problem, fix the C code so that it operates on an argument passed to it rather than a global variable.

If you're okay with with providing your own version of the library, you can refactor out the global variables fairly trivially. This might annoy your users if the library is large enough, though.
Similarly to the above, you can use a different library or write your own.
If you don't want want to do that, and the library can be dynamically linked (ie: libfoo.so) you might be able to load the libary multiple times (one for each instance), although this will probably mean guzzling memory is likely to be unacceptably slow in any serious program
If you have to use this version of this library and it is staticly linked, then you're pretty much screwed.

Related

How to run an object in C++ through a large range of files and functions

Every time when I make projects I have a HUGE data transfer problem. As in my data is unable to get around with the way I've designed things. Is there a "correct" way to transfer data? A more neat and organized way for it to get around? I was taught very often that it is not okay to use global variables because of optimization and whatnot. But something I was never taught was alternates to globals. Is it okay to use a memory address and file that through functions instead of a global variable? For example: let's just pretend there's a huge structure in my header file:
#ifndef DATASTRUCTURE
#define DATASTRUCTURE
struct cat {
int x;
int y;
bool alive;
};
#endif //DATASTRUCTURE
Now I have "a lot" of functions that derive this object.
#ifndef STUFF
#define STUFF
#include "dataStructure.h"
void killcat(cat* c);
void movecatx(cat* c);
void movecaty(cat* c);
#endif STUFF
Now in my main file, I call all those things.
#include <iostream>
#include "dataStructure.h"
#include "stuff.h"
int main()
{
std::cout << "Running!\n";
cat c;
killcat(&c);
movecatx(&c);
movecaty(&c);
}
I watered things way down here. But in a real scenario where you have thousands and thousands of code, Is this a good way to go about things? Having all massive data structures in the main file and then just iterating functions through them?

When to put a whole C++ class framework into a DLL?

I am about to write a C++ framework that will later be used by different C++ applications. The framework will provide one main class, which will be instantiated by the application. That main class will make use of some other classes within the framework. And there will be some helper classes, to be used directly by the application.
Now I am thinking of how I should encapsulate that class framework. I could write the header and source files as usual, and then include those in the applications that will make use of the framework, so that all will be compiled in one go together with the application.
But I am not sure whether this is "the best" approach in my case. Wouldn't it be an option to put the whole framework into a DLL and then link that DLL to the applications? However, I also read that it is often not the best idea to let a DLL export whole classes, and that this approach might lead to difficulties when using STL templates as data members.
Can you recommend an approach to me, maybe something else I have not mentiond above, incl. the pros and cons of all these options?
You can create a C interface using opaque pointers, which is needed in your case because of the varying types and versions of compilers involved. Note that you may not accept or return non-C types, unless you also wrap them in opaque pointers. It's not hard, but there's a bit of work needed on your behalf.
Assuming a class 'YourClass', you would create a YourClassImpl.h and YourClassImpl.cpp (if needed) containing your C++ class code.
YourClassImpl.h
class YourClass
{
private:
int value = 12345;
public:
YourClass() {}
~YourClass() {}
int getThing() { return value; }
void setThing(int newValue) { v = newValue}
};
You would then create a YourClass.h which would be your C header file (to be included by the users of your DLL), containing an opaque pointer typedef and the declarations of your C-style interface.
YourClass.h
#ifdef MAKEDLL
# define EXPORT __declspec(dllexport) __cdecl
#else
# define EXPORT __declspec(dllimport) __cdecl
#endif
extern "C"
{
typedef struct YourClass *YC_HANDLE;
EXPORT YC_HANDLE CreateYourClass();
EXPORT void DestroyYourClass(YC_HANDLE h);
EXPORT int YourClassGetThing(YC_HANDLE h);
EXPORT void YourClassSetThing(YC_HANDLE h, int v);
}
In YourClass.cpp you would define those functions.
YourClass.cpp
#include "YourClass.h"
#include "YourClassImpl.h"
extern "C"
{
EXPORT YC_HANDLE CreateYourClass()
{
return new YourClass{};
}
EXPORT void DestroyYourClass(YC_HANDLE h)
{
delete h;
}
EXPORT int YourClassGetThing(YC_HANDLE h)
{
return h->getThing();
}
EXPORT void YourClassSetThing(YC_HANDLE h, int v)
{
h->setThing(v);
}
}
In your users code they would include YourClass.h.
TheirCode.cpp
#include "YourClass.h"
int ResetValue(int newValue)
{
YC_HANDLE h = CreateYourClass();
auto v = YourClassGetThing(h);
YourClassSetThing(h, newValue);
DestroyYourClass(h);
return v;
}
The most usual way of linking to your DLL would be with LoadLibrary/GetProcAddress - I'd also advise adding a .def file to your project to ensure that the functions are named 'nicely' and are not difficult to access because of any name decoration.
Some issues to keep an eye out for:
Only the standard C fundamental types can be passed back and forth across the interface. Don't use any C++ specific types or classes.
PODs and arrays of PODs may be safe for you to use, but watch out for any packing or alignment issues.
Exceptions must not cross the interface boundaries - catch anything that gets thrown and convert it to a return code or equivalent.
Ensure that memory allocated on either side of the boundary is deallocated on the same side.

Static member initialization using CRTP in separate library

After digging the web, I found some reference to a powerful pattern which exploits CRTP to allow instantiation at run-time of static members:
C++: Compiling unused classes
Initialization class for other classes - C++
And so on.
The proposed approach works well, unless such class hierarchy is placed into an external library.
Doing so, run-time initialization no more works, unless I manually #include somewhere the header file of derived classes. However, this defeats my main purpose - having the change to add new commands to my application without the need of changing other source files.
Some code, hoping it helps:
class CAction
{
protected:
// some non relevant stuff
public:
// some other public API
CAction(void) {}
virtual ~CAction(void) {}
virtual std::wstring Name() const = 0;
};
template <class TAction>
class CCRTPAction : public CAction
{
public:
static bool m_bForceRegistration;
CCRTPAction(void) { m_bForceRegistration; }
~CCRTPAction(void) { }
static bool init() {
CActionManager::Instance()->Add(std::shared_ptr<CAction>(new TAction));
return true;
}
};
template<class TAction> bool CCRTPAction<TAction>::m_bForceRegistration = CCRTPAction<TAction>::init();
Implementations being done this way:
class CDummyAction : public CCRTPAction<CDummyAction>
{
public:
CDummyAction() { }
~CDummyAction() { }
std::wstring Name() const { return L"Dummy"; }
};
Finally, here is the container class API:
class CActionManager
{
private:
CActionManager(void);
~CActionManager(void);
std::vector<std::shared_ptr<CAction>> m_vActions;
static CActionManager* instance;
public:
void Add(std::shared_ptr<CAction>& Action);
const std::vector<std::shared_ptr<CAction>>& AvailableActions() const;
static CActionManager* Instance() {
if (nullptr == instance) {
instance = new CActionManager();
}
return instance;
}
};
Everything works fine in a single project solution. However, if I place the above code in a separate .lib, the magic somehow breaks and the implementation classes (DummyAction and so on) are no longer instantiated.
I see that #include "DummyAction.h" somewhere, either in my library or in the main project makes things work, but
For our project, it is mandatory that adding Actions does not require changes in other files.
I don't really understand what's happening behind the scene, and this makes me uncomfortable. I really hate depending on solutions I don't fully master, since a bug could get out anywhere, anytime, possibly one day before shipping our software to the customer :)
Even stranger, putting the #include directive but not defining constructor/destructor in the header file still breaks the magic.
Thanks all for attention. I really hope someone is able to shed some light...
I can describe the cause of the problem; unfortunately I can't offer a solution.
The problem is that initialisation of a variable with static storage duration may be deferred until any time before the first use of something defined in the same translation unit. If your program never uses anything in the same translation unit as CCRTPAction<CDummyAction>::m_bForceRegistration, then that variable may never be initialised.
As you found, including the header in the translation unit that defines main will force it to be initialised at some point before the start of main; but of course that solution won't meet your first requirement. My usual solution to the problems of initialising static data across multiple translation units is to avoid static data altogether (and the Singleton anti-pattern doubly so, although that's the least of your problems here).
As explained in Mike's answer, the compiler determines that the static member CCRTPAction<CDummyAction>::m_bForceRegistration is never used, and therefore does not need to be initialised.
The problem you're trying to solve is to initialise a set of 'plugin' modules without having to #include their code in a central location. CTRP and templates will not help you here. I'm not aware of a (portable) way in C++ to generate code to initialise a set of plugin modules that are not referenced from main().
If you're willing to make the (reasonable) concession of having to list the plugin modules in a central location (without including their headers), there's a simple solution. I believe this is one of those extremely rare cases where a function-scope extern declaration is useful. You may consider this a dirty hack, but when there's no other way, a dirty hack becomes an elegant solution ;).
This code compiles to the main executable:
core/module.h
template<void (*init)()>
struct Module
{
Module()
{
init();
}
};
// generates: extern void initDummy(); Module<initDummy> DummyInstance
#define MODULE_INSTANCE(name) \
extern void init ## name(); \
Module<init ## name> name ## Instance
core/action.h
struct Action // an abstract action
{
};
void addAction(Action& action); // adds the abstract action to a list
main.cpp
#include "core/module.h"
int main()
{
MODULE_INSTANCE(Dummy);
}
This code implements the Dummy module and compiles to a separate library:
dummy/action.h
#include "core/action.h"
struct DummyAction : Action // a concrete action
{
};
dummy/init.cpp
#include "action.h"
void initDummy()
{
addAction(*new DummyAction());
}
If you wanted to go further (this part is not portable) you could write a separate program to generate a list of MODULE_INSTANCE calls, one for each module in your application, and output a generated header file:
generated/init.h
#include "core/module.h"
#define MODULE_INSTANCES \
MODULE_INSTANCE(Module1); \
MODULE_INSTANCE(Module2); \
MODULE_INSTANCE(Module3);
Add this as a pre-build step, and core/main.cpp becomes:
#include "generated/init.h"
int main()
{
MODULE_INSTANCES
}
If you later decide to load some or all of these modules dynamically, you can use exactly the same pattern to dynamically load, initialise and unload a dll. Please note that the following example is windows-specific, untested and does not handle errors:
core/dynamicmodule.h
struct DynamicModule
{
HMODULE dll;
DynamicModule(const char* filename, const char* init)
{
dll = LoadLibrary(filename);
FARPROC function = GetProcAddress(dll, init);
function();
}
~DynamicModule()
{
FreeLibrary(dll);
}
};
#define DYNAMICMODULE_INSTANCE(name) \
DynamicModule name ## Instance = DynamicModule(#name ".dll", "init" #name)
As Mike Seymour stated the static template stuff will not give you the dynamic loading facilities you want. You could load your modules dynamically as plug ins. Put dlls containing an action each into the working directory of the application and load these dlls dynamically at run-time. This way you will not have to change your source code in order to use different or new implementations of CAction.
Some frameworks make it easy to load custom plug ins, for example Qt.

Avoid creating multiple copies of code in memory

I'm new to developing on embedded systems and am not used to having very little program memory (16kB in this case) to play with. I would like to be able to create global variables, arrays, and functions that I can access from anywhere in the program while only existing in one place in memory. My current approach is to use static class members and methods that I can use by simply including the header file (e.g. #include "spi.h").
What is the best approach for what I'm trying to do?
Here is an example class. From what I understand, variables such as _callback and function definitions like call() in the .cpp will only appear in spi.o so they will appear only once in memory, but I may be mixed up.
spi.h:
#ifndef SPI_H_
#define SPI_H_
#include "msp430g2553.h"
class SPI {
public:
typedef void (*voidCallback)(void);
static voidCallback _callback;
static char largeArray[1000];
static __interrupt void USCIA0TX_ISR();
static void call();
static void configure();
static void transmitByte(unsigned char byte, voidCallback callback);
};
#endif /* SPI_H_ */
spi.cpp:
#include "spi.h"
SPI::voidCallback SPI::_callback = 0;
char SPI::largeArray[] = /* data */ ;
void SPI::configure() {
UCA0MCTL = 0;
UCA0CTL1 &= ~UCSWRST;
IE2 |= UCA0TXIE;
}
void SPI::transmitByte(unsigned char byte, voidCallback callback) {
_callback = callback;
UCA0TXBUF = byte;
}
void SPI::call() {
SPI::_callback();
}
#pragma vector=USCIAB0TX_VECTOR
__interrupt void SPI::USCIA0TX_ISR()
{
volatile unsigned int i;
while (UCA0STAT & UCBUSY);
SPI::call();
}
The data members and the member functions of the class you wrote will only be defined once in memory. And if they're not marked static, the member functions will still only be defined once in memory. Non-static data members will be created in memory once for each object that you create, so if you only create one SPI object you only get one copy of its non-static data members. Short version: you're solving a non-problem.
As per Pete, static won't affect code doubling up, only member vars. In your example, there is 0 difference between static non static memory usage except perhaps for the _callback var (which you call out as an error.) And that one variable would only double up if the class were created more than once.
If you want code to not exist in memory when not in use, look into overlays or some sort of dynamic linking process. DLL type code will probably be major overkill for 16K, but overlays with compressed code might help you out.
Also, beware of extra linked in code from libraries. Closely examine your .map files for code bloat from innocuous function calls. For instance, a single printf() call will link in all sorts of vargs stuff if it is the only thing using it. Same for software floating point (if you don't have a FP unit by default.)

Wrapping C++ class API for C consumption

I have a set of related C++ classes which must be wrapped and exported from a DLL in such a way that it can be easily consumed by C / FFI libraries. I'm looking for some "best practices" for doing this. For example, how to create and free objects, how to handle base classes, alternative solutions, etc...
Some basic guidelines I have so far is to convert methods into simple functions with an extra void* argument representing the 'this' pointer, including any destructors. Constructors can retain their original argument list, but must return a pointer representing the object. All memory should be handled via the same set of process-wide allocation and free routines, and should be hot-swappable in a sense, either via macros or otherwise.
Foreach public method you need a C function.
You also need an opaque pointer to represent your class in the C code.
It is simpler to just use a void* though you could build a struct that contains a void* and other information (For example if you wanted to support arrays?).
Fred.h
--------------------------------
#ifdef __cplusplus
class Fred
{
public:
Fred(int x,int y);
int doStuff(int p);
};
#endif
//
// C Interface.
typedef void* CFred;
//
// Need an explicit constructor and destructor.
extern "C" CFred newCFred(int x,int y);
extern "C" void delCFred(CFred);
//
// Each public method. Takes an opaque reference to the object
// that was returned from the above constructor plus the methods parameters.
extern "C" int doStuffCFred(CFred,int p);
The the implementation is trivial.
Convert the opaque pointer to a Fred and then call the method.
CFred.cpp
--------------------------------
// Functions implemented in a cpp file.
// But note that they were declared above as extern "C" this gives them
// C linkage and thus are available from a C lib.
CFred newCFred(int x,int y)
{
return reinterpret_cast<void*>(new Fred(x,y));
}
void delCFred(CFred fred)
{
delete reinterpret_cast<Fred*>(fred);
}
int doStuffCFred(CFred fred,int p)
{
return reinterpret_cast<Fred*>(fred)->doStuff(p);
}
While Loki Astari's answer is very good, his sample code puts the wrapping code inside the C++ class. I prefer to have the wrapping code in a separate file. Also I think it is better style to prefix the wrapping C functions with the class name.
The following blog posts shows how to do that:
http://blog.eikke.com/index.php/ikke/2005/11/03/using_c_classes_in_c.html
I copied the essential part because the blog is abandoned and might finally vanish (credit to Ikke's Blog):
First we need a C++ class, using one header file (Test.hh)
class Test {
public:
void testfunc();
Test(int i);
private:
int testint;
};
and one implementation file (Test.cc)
#include <iostream>
#include "Test.hh"
using namespace std;
Test::Test(int i) {
this->testint = i;
}
void Test::testfunc() {
cout << "test " << this->testint << endl;
}
This is just basic C++ code.
Then we need some glue code. This code is something in-between C and C++. Again, we got one header file (TestWrapper.h, just .h as it doesn't contain any C++ code)
typedef void CTest;
#ifdef __cplusplus
extern "C" {
#endif
CTest * test_new(int i);
void test_testfunc(const CTest *t);
void test_delete(CTest *t);
#ifdef __cplusplus
}
#endif
and the function implementations (TestWrapper.cc, .cc as it contains C++ code):
#include "TestWrapper.h"
#include "Test.hh"
extern "C" {
CTest * test_new(int i) {
Test *t = new Test(i);
return (CTest *)t;
}
void test_testfunc(const CTest *test) {
Test *t = (Test *)test;
t->testfunc();
}
void test_delete(CTest *test) {
Test *t = (Test *)test;
delete t;
}
}
First, you might not need to convert all your methods to C functions. If you can simplify the API and hide some of the C++ interface, it is better, since you minimize the chance to change the C API when you change C++ logic behind.
So think of a higher level abstraction to be provided through that API. Use that void* solution you described. It looks to me the most appropriate (or typedef void* as HANDLE :) ).
Some opinions from my experience:
functions should return codes to represent errors. It's useful to have a function returning error description in string form. All other return values should be out parameters.
E.g.:
C_ERROR BuildWidget(HUI ui, HWIDGET* pWidget);
put signatures into structures/classes your handles pointer to for checking handles on validness.
E.g. your function should look like:
C_ERROR BuildWidget(HUI ui, HWIDGET* pWidget){
Ui* ui = (Ui*)ui;
if(ui.Signature != 1234)
return BAD_HUI;
}
objects should be created and released using functions exported from DLL, since memory allocation method in DLL and consuming app can differ.
E.g.:
C_ERROR CreateUi(HUI* ui);
C_ERROR CloseUi(HUI hui); // usually error codes don't matter here, so may use void
if you are allocating memory for some buffer or other data that may be required to persist outside of your library, provide size of this buffer/data. This way users can save it to disk, DB or wherever they want without hacking into your internals to find out actual size. Otherwise you'll eventually need to provide your own file I/O api which users will use only to convert your data to byte array of known size.
E.g.:
C_ERROR CreateBitmap(HUI* ui, SIZE size, char** pBmpBuffer, int* pSize);
if your objects has some typical representation outside of your C++ library, provide a mean of converting to this representation (e.g. if you have some class Image and provide access to it via HIMG handle, provide functions to convert it to and from e.g. windows HBITMAP). This will simplify integration with existing API.
E.g.
C_ERROR BitmapToHBITMAP(HUI* ui, char* bmpBuffer, int size, HBITMAP* phBmp);
Use vector (and string::c_str) to exchange data with non C++ APIs. (Guideline #78 from C++ Coding Standards, H. Sutter/ A. Alexandrescu).
PS It's not that true that "constructors can retain their original argument list". This is only true for argument types which are C-compatible.
PS2 Of course, listen to Cătălin and keep your interface as small and simple as possible.
This may be of interest: "Mixing C and C++" at the C++ FAQ Lite. Specifically [32.8] How can I pass an object of a C++ class to/from a C function?