What is the best way to call C/C++ from other languages such as Java, Python, Perl, PHP, etc?
views:
509answers:
4What is the best way to call C/C++ code from other languages such as Java, PHP, Perl, Python, etc?
Use Swig, it allows you to generate code for multiple languages that calls any C/C++ functions. http://www.swig.org/
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.
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.
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;