-1

I am working on a project in which I am trying to make the interaction C code and Python. It means that I want to call the C code in Python. I googled it but the solutions were not understandable for me.

What are the ways to do this?

Fiqra Bazi
  • 13
  • 5
  • Most likely, you want to compile the C code as a shared library and use it from Python via ctypes. There's plenty of examples. – bereal Jan 27 '21 at 08:23
  • There is extensive documentation on extending and embedding, in the Python documentation. Start here https://docs.python.org/3/ and look for the heading **Extending and Embedding** – DisappointedByUnaccountableMod Jan 27 '21 at 08:40

1 Answers1

1

you have to compile your c code as a shared library and you'll be able to call functions using python's ctypes API. here is a simple example on how to do it.

lib.c

__declspec(dllexport) int add(int a, int b);

int add(int a, int b) {
    return a + b;
}

compile (using msvc here)

cl /LD lib.c

app.py

from ctypes import *
lib = cdll.LoadLibrary('lib.dll')
print(lib.add(1, 2))  ## this will print 3

for more see :
https://docs.python.org/3/library/ctypes.html
How can I use a DLL file from Python?
https://www.youtube.com/watch?v=p_LUzwylf-Y&t=277s

thakee nathees
  • 877
  • 1
  • 9
  • 16