Search code examples
pythonpython-3.xdllctypesdllimport

Problems with using C dll in python


I'm trying to import my own made C dll to python code. The function in the dll accepts 10x1 vector of float, return 1 float as result. This is MWE how I try to use it:

from ctypes import*
import numpy as np
mydll = cdll.LoadLibrary(".\Test.dll")
input=[18.1000, 1.1000, 0.2222, 0.2115, 0.0663, 0.5000, 352.0000, 0, 0, 42.0000]
input=np.transpose(input)
result=mydll.Test(input)

This fails with following error:

----> 7 result=mydll.Test(input)
ArgumentError: argument 1: <class 'TypeError'>: Don't know how to convert parameter 1

Can you help me figuring it out? My first idea was that maybe input data does not match but it doesn't matter if I transpose or not, the error is the same.


Solution

  • Get in the habit of always specifying .argtypes and .restype for your functions. the defaults expect integer/pointer inputs and an integer return value. The numpy helper numpy.ctypeslib.ndpointer can help specify the exact type and shape of the required numpy array.

    Example C API and Python code:

    test.c

    #ifdef _WIN32
    #   define API __declspec(dllexport)
    #else
    #   define API
    #endif
    
    API double Test(double* pdata) {
        double sum = 0.0;
        for(int i = 0; i < 10; ++i)
            sum += pdata[i];
        return sum;
    }
    

    test.py

    import ctypes as ct
    import numpy as np
    
    mydll = ct.CDLL('./test')
    mydll.Test.argtypes = np.ctypeslib.ndpointer(dtype=ct.c_double, shape=(10,)),
    mydll.Test.restype = ct.c_double
    data = np.array([18.1000, 1.1000, 0.2222, 0.2115, 0.0663, 0.5000, 352.0000, 0, 0, 42.0000])
    print(mydll.Test(data))
    

    Output:

    414.2