8

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.

Mohit Deshpande
  • 53,877
  • 76
  • 193
  • 251
  • "…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 Answers5

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.

Community
  • 1
  • 1
Alan
  • 45,915
  • 17
  • 113
  • 134
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.

1

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....

vs4vijay
  • 1,175
  • 3
  • 14
  • 28
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
0

To call C/C++ from Java, also give a look at BridJ (it's like JNA with C++ and better performance).

zOlive
  • 1,768
  • 13
  • 11