Calling a function from a DLL that is developed in C ++ with C

Function in dll has prototype below

void Foo(int arg1, int& arg2); 

The question is, how to declare a function prototype in C?

Is the ad legal?

 void Foo(int, int*); 
+5
source share
2 answers

Is the ad legal?

This, but he does not declare the same function. If you need a C API, you cannot use the link. Stick to the pointer and make sure the function has a C link:

 extern "C" void Foo(int, int*) { // Function body } 

If you cannot change the DLL code, you need to write C ++ - a wrapper for it that provides the correct C API.

+8
source

You need an adapter consisting of a C ++ translation block and a header that can be used from both C and C ++, for example (use more convenient names):

adapter.h:

 #ifndef ADAPTER_H #define ADAPTER_H #endif #ifdef __cplusplus extern "C" { #endif void adapter_Foo(int arg1, int *arg2); // more wrapped functions #ifdef __cplusplus } #endif #endif 

adapter.cpp:

 #include "adapter.h" // includes for your C++ library here void adapter_Foo(int arg1, int *arg2) { // call your C++ function, eg Foo(arg1, *arg2); } 

You can compile this adapter into a separate DLL or you can use it as part of your main program. In your C code, simply #include "adapter.h" and call adapter_Foo() instead of Foo() .

+5
source

Source: https://habr.com/ru/post/1271356/


All Articles