'How to use ctypes with Windows?
I'm trying to use some mathematical functions I wrote in C in Python. I have a CMakeLists.txt that builds a shared library using the code. When I build the library in linux and generate the .so library, it works fine. However when I use Windows to generate the .dll library, ctypes says the function doesn't exist.
tools.c
#include "tools.h"
unsigned long long gcd(unsigned long long a, unsigned long long b) {
if (a == 0 || b == 0){
return 0;
}
else if (a == b) {
return a;
}
else if (a > b) {
return gcd(a - b, b);
}
return gcd(a, b - a);
}
unsigned long long factorial(int n){
if(n == 0){
return 1;
}
unsigned long long total = 1;
for(int i = 1; i <= n; i++){
total *= i;
}
return total;
}
tools.h
#ifndef CPYTHON1_TOOLS_H
#define CPYTHON1_TOOLS_H
unsigned long long gcd(unsigned long long a, unsigned long long b);
unsigned long long factorial(int n);
#endif //CPYTHON1_TOOLS_H
CMakeLists.txt
cmake_minimum_required(VERSION 3.16)
project(washmath VERSION 1.0.0)
set(CMAKE_CXX_STANDARD 17)
add_library(${PROJECT_NAME} SHARED tools.c tools.h)
set_target_properties(${PROJECT_NAME} PROPERTIES VERSION ${PROJECT_VERSION})
set_target_properties(${PROJECT_NAME} PROPERTIES SOVERSION ${PROJECT_VERSION_MAJOR})
set_target_properties(${PROJECT_NAME} PROPERTIES PUBLIC_HEADER tools.h)
test.py
from ctypes import CDLL
from ctypes.util import find_library
def main():
c_lib = CDLL(find_library("./washmath"))
print(c_lib.factorial(5))
if __name__ == "__main__":
main()
Linux Output: 120
Windows Output:
File "test.py", line 7, in main
print(c_lib.factorial(5))
File "D:\Program Files\Python\Python310\Lib\ctypes\__init__.py", line 387, in __getattr__
func = self.__getitem__(name)
File "D:\Program Files\Python\Python310\Lib\ctypes\__init__.py", line 392, in __getitem__
func = self._FuncPtr((name_or_ordinal, self))
AttributeError: function 'factorial' not found
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
