In a C program I need to get a reference to a function located in a library written in C++.
Here is the part of the code
// Some C includes
#include <cpplib.h>
.
.
.
// A C structure attribute pointing to the C++ function
infoptr.EXT_meshAdapt = &meshAdapt;
The problem is the compiler tell me there is a undefined reference to meshAdapt
, while when I do the same with a C library there is no problems.
In this thread I saw we can call a C++ function in C by making a wrapper. But is there a way to refer a C++ function without making a wrapper ?
You can use a trailing return type in the declaration or definition of a pointer to a function. For example: auto(*fp)()->int; In this example, fp is a pointer to a function that returns int .
C programming allows passing a pointer to a function. To do so, simply declare the function parameter as a pointer type.
We cannot pass the function as an argument to another function. But we can pass the reference of a function as a parameter by using a function pointer. This process is known as call by reference as the function parameter is passed as a pointer that holds the address of arguments.
Calling a Function Through a Function Pointer in C using function pointer (a) int area = (*pointer)(length); // 3. using function pointer (b) int area = pointer(length);
Usually, compilers in C++ mangles the name of functions. Which means function you write to add two numbers as
int add(int a, int b);
would be mangled. ( means it would look something like @ZVVVZaddDFD
). So, if you want to use this function from C code then you have to call @ZVVVZaddDFD
not add
.
Or better option is to request the compiler to avoid mangling for your functions which you intend to use in C code.
You can do that by :-
extern "C"
{
int add(int a, int b);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With