0

I'm using a Cygwin64 terminal and trying to reference a function from a simple .dll written in C through a wrapper in Python. The goal is to have 'Hello World!' print out on the terminal once I run the python script.

The C file:

// function.c
#include <stdio.h>

int hello()
{
    printf("Hello World!\n");
}

I'm compiling the function into a .dll using gcc:

gcc -c function.c
gcc -shared -o function.dll function.o

Finally, I'm using the ctypes library in python to call the 'hello' function from the compiled .dll file:

# wrapper.py
from ctypes import *
import os

if __name__ == '__main__':
    c_lib = cdll.LoadLibrary(os.path.abspath('function.dll'))
    c_lib.hello()

I'm a novice when it comes to using ctypes, but I've tried several different configuration of the above file, using WinDLL and CDLL; all methods I've tried are resulting in the same output when I run the python script in Cygwin:

$ python wrapper.py
Traceback (most recent call last):
  File "C:\cygwin64\home\Alex\test\marshalling_c_files\wrapper.py", line 6, in <module>
    c_lib = cdll.LoadLibrary(os.path.abspath('function.dll'))
  File "C:\Users\Alex\AppData\Local\Programs\Python\Python39\lib\ctypes\__init__.py", line 452, in LoadLibr
ary
    return self._dlltype(name)
  File "C:\Users\Alex\AppData\Local\Programs\Python\Python39\lib\ctypes\__init__.py", line 374, in __init__
    self._handle = _dlopen(self._name, mode)
OSError: [WinError 193] %1 is not a valid Win32 application

My understanding from looking into this error a little had me thinking that somehow the .dll file I had compiled was not compatible with the version of Cygwin I was running or Windows 10, but I was able to call the 'hello' function from the compiled .dll in another C program.

I've been trying to make this as simple as possible to figure out what's going wrong, but I've stopped making progress on my own. Right now I'm trying to figure out if my .dll is being compiled as 32-bit instead of 64-bit. When I use the -m64 tag for GCC, I'm getting an error saying that the feature is not implemented in GCC for Cygwin.

Alex
  • 1
  • 1
  • 1
    Do you run a 32bit Python version and a 64bit dll ? – Maurice Meyer Jun 22 '21 at 20:38
  • @MauriceMeyer I'm using a 64 bit version of python. I'm not positive if the dll I'm compiling is 32 or 64 bit. I'm trying to run gcc with the option -m64 but I'm getting a message that the feature is not implemented. – Alex Jun 22 '21 at 21:08
  • Does `file function.dll` in cygwin show a version ? – Maurice Meyer Jun 22 '21 at 21:19
  • 1
    @MauriceMeyer function.dll: PE32 executable (DLL) (console) Intel 80386, for MS Windows. Since it's PE32 and not PE32+, it looks like my problem is a 32-bit DLL with a 64-bit version of Python. Am I getting that right? – Alex Jun 22 '21 at 22:55
  • Yes, that's it. – Maurice Meyer Jun 23 '21 at 07:08

0 Answers0