非IT行业的菜鸟,最近用到Python与C联合编程。C函数采用数组变量函数可以实现调用,但改为指针后就出错,
哪位大侠来解答一下。
C 代码:test.c
#include
void show_matrix(int *matrix, int rows)
{
int i;
for (i=0; i
printf("matrix[%d] = %d\n", i, *(matrix+i));
}
}
编译dll。 gcc -o test.dll -shared test.c
python 代码
import numpy as np
from ctypes import *
a = np.asarray(range(16), dtype=np.int32).reshape([4,4])
lib=CDLL('e:\\mysoft\\ctest\\ctypes1\\test.dll')
if not a.flags['C_CONTIGUOUS']:
a = np.ascontiguous(a, dtype=a.dtype) # 如果不是C连续的内存,必须强制转换
aptr=cast(a.ctypes.data, POINTER(c_int))
a1=c_int(8)
lib.show_matrix.argtypes =[POINTER(c_int),c_int]
lib.show_matrix.restype =None
lib.show_matrix(aptr,a1)
编译错误:
Traceback (most recent call last):
File "", line 1, in
File "E:\instal_soft\PyCharm 2018.3.4\helpers\pydev\_pydev_bundle\pydev_umd.py", line 197, in runfile
pydev_imports.execfile(filename, global_vars, local_vars) # execute the script
File "E:\instal_soft\PyCharm 2018.3.4\helpers\pydev\_pydev_imps\_pydev_execfile.py", line 18, in execfile
exec(compile(contents+"\n", file, 'exec'), glob, loc)
File "E:/mysoft/ctest/ctypes1/cintp.py", line 6, in
lib=CDLL('e:\\mysoft\\ctest\\ctypes1\\test.dll')
File "E:\instal_soft\python35\lib\ctypes\__init__.py", line 347, in __init__
self._handle = _dlopen(self._name, mode)
OSError: [WinError 193] %1 不是有效的 Win32 应用程序。