根据[SO]: How to create a Minimal, Complete, and Verifiable example (mcve),您的问题不包含基本信息(例如您的尝试)。确保在下一个更正。
另外,[Python.Docs]: ctypes - A foreign function library for Python。
这是一个说明这个概念的虚拟示例。
dll00.c:
#if defined(_WIN32)
# define DLL_EXPORT __declspec(dllexport)
#else
# define DLL_EXPORT
#endif
DLL_EXPORT int function(int w, int h, unsigned short *pData) {
int k = 1;
for (int i = 0; i < h; i++)
for (int j = 0; j < w; j++, k++)
pData[i * w + j] = k;
return w * h;
}
code00.py:
#!/usr/bin/env python3
import sys
import ctypes as ct
DLL = "./dll00.so"
def print_array(data, h, w):
for i in range(h):
for j in range(w):
print("{:2d}".format(data[i * w + j]), end=" ")
print()
def main(*argv):
dll_dll = ct.CDLL(DLL)
function = dll_dll.function
function.argtypes = [ct.c_int, ct.c_int, ct.POINTER(ct.c_ushort)]
function.restype = ct.c_int
h = 3
w = 5
ArrayType = ct.c_ushort * (h * w) # Dynamically declare the array type: `unsigned short[15]` in our case
array = ArrayType() # The array type instance
print_array(array, h, w)
res = function(w, h, ct.cast(array, ct.POINTER(ct.c_ushort)))
print("{:} returned: {:d}".format(function.__name__, res))
print_array(array, h, w)
if __name__ == "__main__":
print("Python {:s} {:03d}bit on {:s}\n".format(" ".join(elem.strip() for elem in sys.version.split("\n")),
64 if sys.maxsize > 0x100000000 else 32, sys.platform))
rc = main(*sys.argv[1:])
print("\nDone.")
sys.exit(rc)
输出:
[cfati@cfati-5510-0:/cygdrive/e/Work/Dev/StackOverflow/q054753828]> ~/sopr.sh
### Set shorter prompt to better fit when pasted in StackOverflow (or other) pages ###
[064bit prompt]> ls
code00.py dll00.c
[064bit prompt]> gcc -fPIC -shared -o dll00.so dll00.c
[064bit prompt]> ls
code00.py dll00.c dll00.so
[064bit prompt]> python3 code00.py
Python 3.6.4 (default, Jan 7 2018, 15:53:53) [GCC 6.4.0] 064bit on cygwin
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
function returned: 15
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Done.