0

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.

Karls
  • 731
  • 7
  • 17
  • What is the *C* function signature? Please read [\[SO\]: C function called from Python via ctypes returns incorrect value (@CristiFati's answer)](https://stackoverflow.com/a/58611011/4788546). – CristiFati Jan 03 '23 at 17:54
  • Use argtypes and restype to resolve this. This clue should be enough when combined with websearch. – David Heffernan Jan 03 '23 at 18:04

1 Answers1

2

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
Mark Tolonen
  • 166,664
  • 26
  • 169
  • 251