C ++ API - the right approach

I need to create an API for C ++, a framework that performs some simulations. I already created a new class with __declspec(dllexport) functions and created a framework for the DLL. This works fine and I can use the framework in a C # application. But is there a different or better approach for creating an API with C ++?

+4
source share
2 answers

The export class solution has some serious drawbacks. You cannot write DLLs in other languages ​​because they do not support name management. In addition, you cannot use other compilers except VS (for the same reason). In addition, you cannot use another version of VS, because MS does not guarantee that the carriage mechanism remains unchanged in different versions of the compiler.

I would suggest using a flattened C-style interface, for example.

 MyClass::Method(int i, float f); 

Export as:

 MyClass_MyMethod(MyClass * instance, int i, float f); 

You can wrap it inside C # to create a class again.

+1
source

If you want to create a C ++ API, then you can export a set of classes from the DLL / shared library. Many C ++ libraries decide to offer a C interface because pure C interfaces are much easier to associate with foreign languages. To associate foreign languages ​​with C ++, a cover generator such as SWIG is usually required.

C ++. The API also has a problem due to the fact that due to the C ++ name change, the same compiler / linker must be used to create the framework and the application.

It is important to note that the __declspec(dllexport) mechanism, which __declspec(dllexport) compiler that the class should be exported, is specific to Microsoft Compiler. A common practice is to put it in a preprocessor macro in order to be able to use the same code for other compilers:

  #ifdef _MSC_VER # define MY_APP_API __declspec(dllexport) #else # define MY_APP_API #endif class MY_APP_API MyClass {} 
+3
source

All Articles