Many of today's programming languages are based on C; like C++, C#, Java, Objective-C. So could I call a C method from C++ code? Or call C from Java or C#? Or is this goal out of reach and unreasonable? Please include a quick code sample for my and everyone else's understanding.
            Asked
            
        
        
            Active
            
        
            Viewed 1,246 times
        
    8
            
            
        - 
                    "…are based on C; like…C#, Java…" -- Are they? I think this is limited to curly braces and semicolons in those cases. – sellibitze Jun 13 '10 at 08:22
- 
                    agree, syntax resemblance does not mean they are based on C even if they could be (or could have been as C++); C has no methods. C++ and Objective-C can call C functions and link to C-written libraries without problems. – ShinTakezou Jun 13 '10 at 09:48
5 Answers
5
            C++,C#, Objective-C, and Java can all call C routines. Here are a few links that will give you an overview of the process needed to call C from each language you asked about.
- 
                    Can it call C routines from just compiled C code. Or does the C code have to be in a library? – Mohit Deshpande Jun 13 '10 at 07:52
- 
                    C++ and Objective-C can compile C, as they are both supersets. C# and Java will require C code to exist in libs – Alan Jun 13 '10 at 07:55
- 
                    the article about java is not about calling c from java but calling java from c – ManBugra Jun 13 '10 at 08:20
2
            
            
        An example of calling C from C++. Save this C function in a file called a.c:
int f() {
   return 42;
}
and compile it:
gcc -c a.c
which will produce a file called a.o. Now write a C++ program in a file called main.cpp:
#include <iostream>
extern "C" int f();
int main() {
   std::cout << f() << std::endl;
}
and compile and link with:
g++ main.cpp a.o -o myprog
which will produce an execuatable called myprog which prints 42 when run.
0
            
            
        To call C methods from Java, there are multiple options, including:
- JNA - Java Native Access. Free. Easy to use. Hand-declaration of Java classes and interfaces paralleling existing C structs and functions. Slower than JNI - by a few hundred nanoseconds per call.
- JNI - Java Native Interface. Free. Fastest option. Requires a layer of native glue code between your Java code and the native functions you want to call.
- JNIWrapper - Commercial product, similar to JNA.
 
    
    
        Andy Thomas
        
- 84,978
- 11
- 107
- 151
 
     
     
     
    