How to call a C++ function from C code - c++

I have a C++ class with its header CFileMapping.cpp and CFileMapping.h I want to call the c++ function CFileMapping::getInstance().writeMemory( ) in my C code.
Even when I wrapped my C++ code and added
#ifdef __cplusplus
extern "C"
in the header file to deal with the c++ code and added
extern "C"
in the cpp file, I still can't call my function like this
CFileMapping::getInstance().writeMemory().
Could any one help me? I want to keep my c++ code and be able to call it when I want.

You should create C wrapper for your C++ call:
extern "C"
{
void WriteMemFile()
{
CFileMapping::getInstance().writeMemory( );
}
}
// The C interface
void WriteMemFile();
IMPORTANT: The extern "C" specifies that the function uses the C naming conventions.

Related

Swift Bridging header from C++ is not Working

My need was that I want to call a swift function from my cpp code. I have tried Using Bridging method for this purpose. When I try to call a swift from c it is working. Since C and C++ are similar, I used the same logic in C++ ,but it is not working.
Compilation of this CPP code gives error like
Undefined symbol: sayHello()
.
My c and c++ sample code is like this ,
CToSwift-Bridging-Header.h
void callCpp();
extern void sayHello();
main.c/.cpp
#include <stdio.h>
#include "CToSwift-Bridging-Header.h"
int main(int argc, const char * argv[]) {
printf("Hello, Main!\n");
callCpp();
return 0;
}
void callCpp() {
printf("CPP: Hi This is C\n");
printf("CPP: Swift say hello to everyone !\n");
sayHello();
printf("CPP: Nice! ");
}
Testswift.swift
import Foundation
#_cdecl("sayHello")
func sayHello()
{
print ("Swift:Hello , Welcome to Swift")
}
After reading some available documentation for this concept, I understand Swift (Obj c) and C++ is not directly related since both are evolved from C on different manner.
But my queries are
1] Is something else which I am missing in this Bridging header method to call a swift function from a C++ Code?
2] Is there any other Method to achieve my goal ?
3] Can we able to pass the swift code as a library or dll when compiling C++ ?
This looks like a name mangling issue.
C++ adds information to the name of each function that encodes the parameter and return types so that overloading with different parameter types works.
The normal trick to include C headers (which your bridging header is effectively) is an extern "C" { ... } If I remember correctly from my C++ programming days 20 years ago, it should go like this:
#ifdef __cplusplus
void callCpp();
extern "C" {
#endif
extern void sayHello();
#ifdef __cplusplus
}
#endif
Everything inside the extern "C" { ... } will be treated by the C++ compiler as straight C and so no name mangling will be done. The compiler will remember this if it encounters the function implementation inside C++ code and will apply no name mangling to it either so the extern declaration and the implementation have matching names.
The ifdefs stop C (and Swift) from seeing the C++ extern "C" { ... }.
On the assumption that you want callCpp() to use C++ conventions, I've put it outside the extern "C" but inside the ifdef so it is not visible to C and Swift programs.

Calling C functions within C++

I have a medium length C file with a bunch of functions (NOT under a header file - just a bunch of functions), that I wish to gather and use under a C++ project I'm developing.
Now I've read about the extern function but I've only seen it work on small C functions that are under a .h file.
But I wish to include these functions without messing with the C files themselves since I don't really understand them - I just need the function "under the hood". Is there any easy simple solution to this problem?
Yes, you just need some extern "C" declarations visible in your C++ code:
extern "C" {
int my_C_function_1(void);
int my_C_function_2(void);
}
This can either go in a suitable header, or if it's only used within one particular .cpp file then you could just put it there.
Note that if your C functions are already declared within a C header somewhere you can just do this within your .cpp file:
extern "C" {
#include "my_C_header.h"
}
You need to make a C++ header file myheader.hh. It starts with
#ifndef MYHEADER_INCLUDED
#define MYHEADER_INCLUDED
extern "C" {
then you declare all your public C functions, types, macros, etc.... At last you end it with
}; // end extern C
#endif MYHEADER_INCLUDED
In your C++ program, add #include "myheader.hh"
Alternatively (and instead of using myheader.hh), you might add (after other includes, but before C++ code) in your C++ file something like
extern "C") {
#include "your-C-code.c"
};
(But it might not work).
You'll need to declare the functions, typically in a header file, in order to call them from C++. If you compile these functions with a C compiler, then you will indeed need to surround the declarations with extern "C"; e.g.
extern "C" {
int foo(int, int);
}
If you have the source, then you could also modify it to include the header file (sans extern "C") and compile the functions with your C++ compiler.

Calling C++ functions from C file

I am quite new to C and C++. But I have some C++ functions which I need to call them from C. I made an example of what I need to do
main.c:
#include "example.h"
#include <stdio.h>
int main(){
helloWorld();
return 0;
}
example.h:
#ifndef HEADER_FILE
#define HEADER_FILE
#ifdef __cplusplus
extern "C" {
#endif
void helloWorld();
#ifdef __cplusplus
}
#endif
#endif
example.cpp:
#include <iostream.h>
void helloWorld(){
printf("hello from CPP");
}
It just doesn't work. I still receive the error of undefined reference to _helloWorld in my main.c. Where is the the problem?
Short answer:
example.cpp should include example.h.
Longer answer:
When you declare a function in C++, it has C++ linkage and calling conventions. (In practice the most important feature of this is name mangling - the process by which a C++ compiler alters the name of a symbol so that you can have functions with the same name that vary in parameter types.) extern "C" (present in your header file) is your way around it - it specifies that this is a C function, callable from C code, eg. not mangled.
You have extern "C" in your header file, which is a good start, but your C++ file is not including it and does not have extern "C" in the declaration, so it doesn't know to compile it as a C function.
the extern "C" tells C++ that the declared function has to use the C ABI (Application Binary interface), hence, whether the language is C or C++, your void HelloWorld() is always seen externally as it is C.
But you implemented it in the cpp file like it is a C++ one, C is not aware of.
You have to make the prototype of HelloWorld coherent for both C and C++, so the cpp file should declare it as extern "C" void Helloworld() { /*your code here*/ }, or simply, #include "example.h" from example.cpp, so that, before implementing it, the compiler already knows it has to follow the C convention.

c and c++ mixed

I need to call cpp method from c file.
I have written this interface for that..
cpp file
extern "C" void C_Test(int p){
Class::CPP_Test(p);
}
c file
extern void C_Test(int p);
void C_Function(){
C_Test(10); //error
}
I get error in c file "undefined reference to C_Test(int)"
any idea whats wrong?
You must declare extern only for function prototype, and ensure to link correctly. In addiction to this, CPP_Test(p) must be a static member of Class, otherwise your code does not work. At last, extern "C" must enclose in brackets its content, more like
extern "C"
{
void C_Test(int p)
{
Class::CPP_Test(p);
}
}
Tell us if this works.
Are you compiling both with a C++ compiler? C++ compilers may compile a C-source file as C++, in which case it will perform name mangling, so you need to be sure to compile the C source file with a C compiler.
I am using C++ compiler for both types of files.
Without "C" it works!! Also without extern "c" it works!

Impact of using extern "C" { on C++ code when using g++

When using G++ (e.g. version 4.5 on Linux) can anyone explain what will/can happen if a user writes a header file for a mixed C/C++ system like this:
#ifdef __cplusplus
extern "C" {
int myCPPfunc(some_arg_list....); /* a C++ function */
}
#endif
but here myCPPfunc() is a normal C++ function with a class def inside - i.e. it was wrongly labeled as a C function.
What is the impact of this?
The main impact of this is that you cannot overload it, e.g. this is legal:
int myCPPfunc(int a);
int myCPPfunc(char a);
But this is not:
extern "C"
{
int myCPPfunc(int a);
int myCPPfunc(char a);
}
It is perfectly legitimate to have the implementation of an extern "C" function use arbitrary C++ features. What you can't do is have its interface be something you couldn't do in C, e.g. argument overloading, methods (virtual or otherwise), templates, etc.
Be aware that a lot of the "something you couldn't do in C" cases provoke undefined behavior rather than prompt compile errors.
This tells the C++ compiler that the functions declared in the header file are C functions.
http://www.parashift.com/c++-faq-lite/mixing-c-and-cpp.html#faq-32.2
This is exactly what extern "C" is for - it allows you to write a C++ function that can be called from C.
Essentially, that declaration is telling the C++ compiler that you want the C++ function myCPPfunc() to have an external interface that is linkable (and therefore callable) from C.
The implementation of the function is still C++ and can still use C++ features.
Typically, the declaration of the function in the header file might look more like:
#ifdef __cplusplus
extern "C" {
#endif
int myCPPfunc(some_arg_list....); /* a C++ function */
#ifdef __cplusplus
}
#endif
That lets the same header file be used by either the C++ compiler or the C compiler, and each will see it as declaring a C callable function.