0

I'm trying to speed up parts of my python code by calling c++ code using ctypes. I found many step-by-step guides, including some on this website. However, basically all of them assume linux operating systems and I am working with windows.

Based on some of the linux examples and some googling, I created the following MWE:

myfunc.cpp

extern "C" 
int timestwo(int mynum){
    return mynum*2;
}

I compile this with:

gcc -shared -o myfunc.dll myfunc.cpp

Then, I try to load the DLL file with python using:

usefunc.py

import ctypes
from os.path import abspath

dll = ctypes.CDLL(abspath('myfunc.dll'))

However, this gives the following error message:

OSError: [WinError 193] %1 is not a valid Win32 application

Edit: Solved. The problem was that I was generating a 32 bit DLL while using 64 BIT python. I re-installed MINGW64 with the following settings:

Architecture: x86_64
Threads: Win32
Exception: Seh

This solved the problem.

user3053216
  • 777
  • 1
  • 9
  • 24
  • 1
    you can try building this code using VS code on windows, it will take care of the building process, then try to consume the .dll file. – kshitij chaurasiya Jul 22 '21 at 09:20
  • 2
    As per [this answer](https://stackoverflow.com/a/27910041/3228591), is it possible that you're building a 64-bit DLL and loading it with 32-bit Python (or vice versa)? – Kemp Jul 22 '21 at 09:24
  • @kemp: I use gcc.exe instead of mingw32-gcc.exe and when I start the python console it says: " [MSC v.1916 64 bit (AMD64)] on win32". So I think this should mean that both are 64 bit, but I'm definitely not sure. – user3053216 Jul 22 '21 at 09:40
  • 2
    You can use DUMPBIN to verify the bitness of your DLL. Once you have the bitness issues sorted out your DLL will have to actually export a symbol. Right now it doesn't. You'll probably want to use `__declspec(dllexport)` as the simplest way. – IInspectable Jul 22 '21 at 09:58
  • @IInspectable, Thank you for the comment. I ran it, and it said 32 bit word machine. So I guess it's not compiles as 64 bit. However, i downloaded the latest version of mingw-w64 and used that to compile. The results remains the same. Am I checking things correctly? If so, how can I compile as 64 bit? Thanks in advance! – user3053216 Jul 22 '21 at 10:22
  • 1
    Using DUMPBIN is simple: `dumpbin /HEADERS myfunc.dll | findstr "machine"`. If that outputs that the binary is 32bits then that's the case. I'm not familiar with MinGW-w64, so I cannot help you there. – IInspectable Jul 22 '21 at 11:07
  • @IInspectable Thanks for the help. It was the 32 bit, and I found out my mingw installation was wrong. – user3053216 Jul 22 '21 at 11:32

0 Answers0