Reputation: 5141
I have been doing a lot of reading on this subject and am having a lot of trouble wrapping my brain around how this needs to happen.
What I want to do is have a function:
int Add(int a, int b) { return a + b; }
And be able to call it from my Python scripts. How do I do this?
Upvotes: 4
Views: 337
Reputation: 53819
If you just want to implement part of your code in C, I'd recommend using cython. For example, you could write your Add
function like so:
cpdef int Add(int x, int y):
return x+y
And then use cython to compile it into a module you can import into your code.
Upvotes: 2
Reputation: 400146
The proper way is to write an extension module. But if you're doing simple stuff (such as adding two integers) than can be done independently of Python, you can just write a regular shared library in C (which would be a DLL on Windows), and load it using the ctypes module.
For example:
// C code
int Add(int a, int b) { return a + b; }
Compile that like this:
gcc add.c -fPIC -shared -o libadd.so
Then use it in Python like this:
import ctypes
libadd = ctypes.cdll.LoadLibrary('libadd.so')
libadd.Add.argtypes = [ctypes.c_int, ctypes.c_int]
libadd.Add.restype = ctypes.c_int
print libadd.Add(42, 1) # Prints 43
Upvotes: 7
Reputation:
The easiest way by far is using the ctypes module, which will allow you to call functions in C libraries directly from Python. Once you have your C function compiled as a library, you can write something to the effect of:
# Load ctypes, and your library
from ctypes import *
mylib = CDLL("mylibrary.so")
# Declare the function's prototype. This isn't strictly required.
mylib.Add.argtypes = [c_int, c_int]
mylib.Add.restype = c_int
# Call it!
result = mylib.Add(123, 456)
Upvotes: 9
Reputation: 7780
Have you tried pyrex? It lets your write in a python-similar syntax that will then be compiled to a C extension module.
The quick-quide should get you started easily and is full of real world examples.
Upvotes: 2
Reputation: 375484
There are a few ways to go about it. The classic Python C API is a little complicated, but is the source of all Python. You can get started with: A Whirlwind Excursion through Python C Extensions.
Upvotes: 2