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.
-
"…are based on C; like…C#, Java…" -- Are they? I think this is limited to curly braces and semicolons in those cases.sellibitze– sellibitze2010-06-13 08:22:35 +00:00Commented Jun 13, 2010 at 8: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– ShinTakezou2010-06-13 09:48:54 +00:00Commented Jun 13, 2010 at 9:48
5 Answers
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.
3 Comments
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.
Comments
To Call C Methods In Java...
there a Keyword "native" in Which You can write machine-dependent C code and invoke it from Java....
Basically it creates a DLL file..then u have to load it in ur program...
a nice example here....
Comments
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.
Comments
To call C/C++ from Java, also give a look at BridJ (it's like JNA with C++ and better performance).