Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get a pointer to C++ function library in c program

Tags:

c++

c

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 ?

like image 912
Phantom Avatar asked Apr 27 '16 07:04

Phantom


People also ask

How do you use a pointer to a function in C?

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 .

Can you pass a pointer to a function in C?

C programming allows passing a pointer to a function. To do so, simply declare the function parameter as a pointer type.

Can we have a pointer to a function?

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.

How do you call a function from a function pointer?

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);


1 Answers

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);
}
like image 85
ravi Avatar answered Sep 19 '22 07:09

ravi