7

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.

2
  • "…are based on C; like…C#, Java…" -- Are they? I think this is limited to curly braces and semicolons in those cases. Commented 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. Commented Jun 13, 2010 at 9:48

5 Answers 5

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Can it call C routines from just compiled C code. Or does the C code have to be in a library?
C++ and Objective-C can compile C, as they are both supersets. C# and Java will require C code to exist in libs
the article about java is not about calling c from java but calling java from c
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.

Comments

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

Comments

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.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.