0

Well given a C code , is there a way that i can use other languages like python to execute the C code . What i am trying to say is , there are soo many modules which are built using a language , but also offer access via different languages , is there any way to do that ?

asked Nov 3, 2010 at 12:57

2 Answers 2

2

Of course, it's called "extending" in the Python world. The official documentation is here. A short excerpt:

This document describes how to write modules in C or C++ to extend the Python interpreter with new modules. Those modules can define new functions but also new object types and their methods. The document also describes how to embed the Python interpreter in another application, for use as an extension language. Finally, it shows how to compile and link extension modules so that they can be loaded dynamically (at run time) into the interpreter, if the underlying operating system supports this feature.

An even easier way for Python would be using the ctypes standard package to run code in DLLs.

answered Nov 3, 2010 at 13:00
Sign up to request clarification or add additional context in comments.

Comments

1

Many ways. Generically, this is often called a Foreign Function Interface. That Wikipedia page says the following about Python:

* The major dynamic languages, such as Python, Perl, Tcl, and Ruby,

all provide easy access to native code written in C/C++ (or any other language obeying C/C++ calling conventions). o Python additionally provides the Ctypes module 2, which can load C functions from shared libraries/DLLs on-the-fly and translate simple data types automatically between Python and C semantics. For example:

 import ctypes libc = ctypes.CDLL('/lib/libc.so.6' ) # under Linux/Unix
 t = libc.time(None) # equivalent C code: t = time(NULL)
 print t

A popular choice that supports many languages is SWIG

answered Nov 3, 2010 at 13:02

2 Comments

i guess SWIG will be a direct approach. but will i have an inadvertent data loss while using the c/c++ code as python module , for example, when i use STLs and try to pass the values to python data types.
@Rahul: didn't you ask about C? Then, what has the STL to do with it? Anyhow, read about SWIG's support for the STL here: swig.org/Doc1.3/Library.html#Library_stl_cpp_library

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.