PEP 3118 warning when using ctypes array as numpy array

岁酱吖の 提交于 2019-11-30 12:45:17

It's a bug in Python. ctypes currently produces invalid PEP 3118 type codes, which Numpy notices: http://bugs.python.org/issue10746 http://bugs.python.org/issue10744

When such an inconsistency is present, Numpy skips using the PEP 3118 buffer interface, and falls back to the old (obsolete) buffer interface. This should work properly.

You can silence the warning using Python's warnings module. However, the warning may have a performance impact.

You can also try working around the issue by wrapping the ctypes object in buffer().

There is a more convenient way of doing this, which avoids the warning altogether:

Instead of creating the data as a ctypes array first and then converting it to a NumPy array, just create it as a NumPy array right away, and then use numpy.ctypeslib.ndpointer as type specifier in your ctypes prototype. As an example, let's say you have a C function called f which takes a char* and a size_t as arguments:

void f(char* buf, size_t len);

Your ctypes prototype would be

from numpy.ctypeslib import ndpointer
some_dll = ctypes.CDLL(...)
some_dll.f.argtypes = [ndpointer(numpy.uint8, flags="C_CONTIGUOUS"),
                       ctypes.c_size_t]
some_dll.f.restype = None

and you can call this function as

a = numpy.zeros(10, numpy.uint8)
f(a, a.size)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!