Skip to content

techtrendings.com

Let's explore

Menu
Menu

Calling C++ function from C

Posted on November 10, 2022November 10, 2022 by Avidlearner

To Call a C++ function from C , you need to use extern “C” with the C++ function and call it from your C/C++ code. The extern "C" line tells the compiler that the external information sent to the linker should use C calling conventions and name mangling. Below is the implementation:

// C++ code:

extern "C" void fun(char);

void fun(char x)
{
// ...
}
fun() can be used like this below

/* C code: */

void fun(char);

void cCode(char x)
{
fun(x);
/* 
.
.
. */
}

This works only for non-member functions. If you want to call member functions (including virtual functions) from C, you need to provide a simple wrapper. See the below implementation:

// C++ code:

class CCall {
// declare something
virtual int fun(char);
};

extern "C" int call_C_fun(CCall* p, char x) // wrapper function
{
return p->fun(x);
}
Now fun() can be used like below:

/* C code: */

double call_C_fun(struct CCall* p, char x);

void ccCall(struct CCall* p, char x)
{
double d = call_C_fun(p,x);
/* ... */
}

If you want that you have to call overloaded functions from your C program, you must provide wrappers with different names for the C code to use. For example:

// C++ code:

void fun(char);
void fun(int);

extern "C" void fun_c(char x) { fun(x); }
extern "C" void fun_i(int i) { fun(i); }
Now the fun() can be used like this:

/* C code: */

void fun_i(int);
void fun_c(char);

void ccccode(int i,char x)
{
fun_i(i);
fun_c(c);
/* ... */
}

Related

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Recent Posts

  • Implement Trie Data Structure in C++- LeetCode
  • How TLS Works
  • C++ – Factory Design Pattern – Creation Design Pattern
  • C++ – Strategy Design Pattern – Behavioral Design Pattern
  • LFU Cache Implementation – LeetCode

Recent Comments

  • automatically like friends photos on instagram on Program to find unpaired element in an Array in C++|Leetcode |techtrendings
  • Twicsy on Program to find unpaired element in an Array in C++|Leetcode |techtrendings

Archives

  • January 2023
  • November 2022
  • August 2022
  • June 2022
  • May 2022
  • March 2022
  • February 2022
  • January 2022

Categories

  • Algorithm
  • Algorithm
  • C++
  • Design Patterns
  • Multithreading
  • OS Concepts
  • Programming
  • Uncategorized

Meta

  • Log in
  • Entries feed
  • Comments feed
  • WordPress.org

Join Our Mailing List for the Latest News and Updates.

© 2023 techtrendings.com | Powered by Superbs Personal Blog theme