0

I need to call a certain function written in C in my python code using the ctypes library to call a shared object .so. So I followed this (apparently) simple guide.

the C file / function:

#include <stdio.h>

int square(int i) {
    return i * i;
}

the python file:

from ctypes import *

so_file = "C:/PY2C/my_functions.so"

my_functions = CDLL(so_file)

print(type(my_functions))
print(my_functions.square(10))

print("done")

and I got the following errors:

File "C:\PY2C\calling_c_functions.py", line 5, in <module>
    my_functions = CDLL(so_file)
  File "C:\Users\myname\AppData\Local\Programs\Python\Python38\lib\ctypes\__init__.py", line 369, in __init__
    self._handle = _dlopen(self._name, mode)";
OSError: [WinError 193] %1 non è un'applicazione di Win32 valida

Why python can't read the .so shared object? How can I solve this simple task?

dbush
  • 205,898
  • 23
  • 218
  • 273
  • Can a C program load this library? I notice its a .so when you want .dll for windows. – tdelaney Nov 15 '21 at 19:05
  • You can't load `.so` files on Windows: https://stackoverflow.com/a/3233786/6273251. It has to be a `.dll`. `.so` files are only for Unix-like systems from what I can tell. – Random Davis Nov 15 '21 at 19:11
  • @tdelaney so basically I need to create a .dll and python would be able to access my C file. Is this right? It seems that creating a .dll file is way less straightforward that a .so in linux.... – Gaetano Veti Nov 15 '21 at 19:18
  • WinError 193, "C:\PY2C\calling_c_functions.py" - this code is running on windows, not linux. – tdelaney Nov 15 '21 at 19:26
  • @tdelaney In layman terms what should I do? – Gaetano Veti Nov 15 '21 at 19:37
  • Are you running on Windows? I'm not sure how you built the .so in the first place. One option is to use python's packaging services to bundle .C and .py files - the .C files can be compiled for you. See https://docs.python.org/3/distributing/index.html. There is history here... setuptools begat distulits begat wheels. I'd search for examples of distributing .C files in wheels. You'll write a setup.py to describe the project. – tdelaney Nov 15 '21 at 19:57
  • I'm running in windows yes. And I only have found this procedure to perform this type of task (https://www.youtube.com/watch?v=zoX7N3_DbcE&ab_channel=MySirG.com) this is another guide equivalent to the first one I've posted. I will search for the terms you suggested me anyway... – Gaetano Veti Nov 15 '21 at 21:58

0 Answers0