tags:

views:

509

answers:

4

What is the best way to call C/C++ from other languages such as Java, Python, Perl, PHP, etc?

+1  A: 

Use Swig, it allows you to generate code for multiple languages that calls any C/C++ functions. http://www.swig.org/

Jared
So, in the minute that passed between you asking and answering your own question, you downloaded swig, played around with it and found it to be a good solution to your problem domain?
kasperjj
@kasperjj: see http://stackoverflow.com/questions/2572/is-it-poor-etiquette-to-answer-your-own-question
CesarB
Cool... was not aware of this :-)
kasperjj
unfortunately, swig not always works as expected, especially on "strange" unices like AIX
Davide
+2  A: 

That really depends on the language... some languages can bind directly to c/c++ libraries, others such as java needs to have explicit interfaces written. If you are trying to solve a specific problem, I would suggest that you provide more details about what you are trying to do.

kasperjj
+2  A: 

It's going to depend on the language and what sort of integration you want.

All of those languages will let you execute an system command, so you could build your C into an executable, and invoke it like a command. In Python:

os.system("myccode -v args etc")

The downside of this method is that you don't share any memory state, or return much information, and you have the overhead of spinning up a process. On the plus side, it's usable everywhere, and very low-tech.

Each language has their own mechanism for invoking C within the same process. Python for example has C API, and you can build your C code into a Python extension. This allows for a very tight integration, but is more work, both in learning the C API, and in carefully writing the code to not leak memory.

Python also provides ctypes, which can invoke C DLLs. This is a bit easier than a full C extension, but doesn't provide all the same opportunities for integration.

Ned Batchelder
+8  A: 

From Perl

Inline::C
Inline::CPP
Inline::Java
Inline::Python
Inline::Lua

excerpt from Inline::C-Cookbook:

use Inline C => <<'END_C';

  void greet() {
    printf("Hello, world\n");
  }
END_C

greet;
Brad Gilbert