How would I import a winDLL into python and be able to use all of its functions? It only needs doubles and strings.
You've tagged the question ctypes and so it sounds like you already know the answer.
The ctypes tutorial is excellent. Once you've read and understood that you'll be able to do it easily.
For example:
>>> from ctypes import *
>>> windll.kernel32.GetModuleHandleW(0)
486539264
And an example from my own code:
lib = ctypes.WinDLL('mylibrary.dll')
#lib = ctypes.WinDLL('full/path/to/mylibrary.dll')
func = lib['myFunc']#my func is double myFunc(double);
func.restype = ctypes.c_double
value = func(ctypes.c_double(42.0))
I'm posting my experience. First of all despite all the hard work that take me to put all pieces together, importing a C# dll is easy. The way I did it is:
1) Install this nuget package (i'm not owner, is just very useful) in order to build a unmanaged dll: https://sites.google.com/site/robertgiesecke/Home/uploads/unmanagedexports
2) Your C# dll code is like this:
using System;
using RGiesecke.DllExport;
using System.Runtime.InteropServices;
public class MyClassName
{
[DllExport("MyFunctionName",CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.LPWStr)]
public static string MyFunctionName([MarshalAs(UnmanagedType.LPWStr)] string iString)
{
return "hello world i'm " + iString
}
}
3) Your python code is like this:
import ctypes
#Here you load the dll into python
MyDllObject = ctypes.cdll.LoadLibrary("C:\\My\\Path\\To\\MyDLL.dll")
#it's important to assing the function to an object
MyFunctionObject = MyDllObject.MyFunctionName
#define the types that your C# function return
MyFunctionObject.restype = ctypes.c_wchar_p
#define the types that your C# function will use as arguments
MyFunctionObject.argtypes = [ctypes.c_wchar_p]
#That's it now you can test it
print(MyFunctionObject("Python Message"))
Using WinDLL
(and wintypes
, msvcrt
) is windows specific imports and does not always work, even on windows! The reason is that it depends on your python installation. Is it native Windows (or using Cygwin or WSL)?
For ctypes, the more portable and correct way is to use cdll
like this:
import sys
import ctypes
from ctypes import cdll, c_ulong
kFile = 'C:\\Windows\\System32\\kernel32.dll'
mFile = 'C:\\Windows\\System32\\msvcrt.dll'
try:
k32 = cdll.LoadLibrary(kFile)
msvcrt = cdll.LoadLibrary(mFile)
except OSError as e:
print("ERROR: %s" % e)
sys.exit(1)
# do something...
Use Cython, both to access the DLLs, and to generate Python bindings for them.