I am currently working to get some intuition about interfacing C-Code
to Python
. For interfacing C-code to Python, I am using ctypes module and following these implementations such that:
As we know that
The ctypes module provides C compatible data types and functions to load DLLs so that calls can be made to C shared libraries without having to modify them.
I have just implemented a simple function using C
and generated " Shared Library " of the file using these commands on Cygwin:
For Linux,
- cc -fPIC -shared -o libfunc.so function.c
- gcc -shared -Wl,-soname,adder -o adder.so -fPIC function.c
On Windows, assuming that you have GCC installed:
1 ~ $ gcc -std=c11 -Wall -Wextra -pedantic -c -fPIC function.c -o libfunc.o
2 ~ $ gcc -shared libfunc.o -o libfunc.dll
Then I placed all the files in the same directory. Following are given files:
- function.c
- libfunc.so
- Testing.py
function.c
int func(int num)
{
if (num == 0)
return 0;
else
return 1;
}
Testing.py
import os
import ctypes
from ctypes.util import find_library
num = 16
# To verify that Library is available in the specified path
pathToWin32Environment = os.getcwd()
pathToDll = pathToWin32Environment + "\\libfunc.so"
if not os.path.exists(pathToDll):
raise Exception('Could not locate ' + pathToDll)
curr_dir_before = os.getcwd()
os.chdir(pathToWin32Environment)
# print("Available library:", find_library('libfunc.so'))
Lib_func = ctypes.cdll.LoadLibrary("F:/PythonCodeBase/NetEQ/libfunc.so")
# Lib_func = ctypes.CDLL(F:/PythonCodeBase/NetEQ/libfunc.so")
# Lib_func = ctypes.windll.LoadLibrary("libfunc.so")
Lib_func.func.argtypes(ctypes.c_int)
ret_val = Lib_func.func(num)
print(ret_val)
I have tried many times, either I'm giving the full Specified path
or simple (.so) filename
. Every time, I just got these types of errors.
- FileNotFoundError: Could not find module 'F:\PythonCodeBase\NetEQ\libfunc.so'. Try using the full path with constructor syntax.
- FileNotFoundError: Could not find module 'libfunc.so'. Try using the full path with constructor syntax.
I have done multiple attempts using PyCharm IDE
as well as Command Prompt
but the same error appears.
Please assist me accordingly.