python 调用C函数的dll文件传递指针变量时错误

逆风行天下 发布于 04/14 10:26
阅读 65
收藏 0

非IT行业的菜鸟,最近用到Python与C联合编程。C函数采用数组变量函数可以实现调用,但改为指针后就出错,

哪位大侠来解答一下。

 

C 代码:test.c

#include <stdio.h>

 

void show_matrix(int *matrix, int rows)

{

int i;

for (i=0; i<rows; 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 "<input>", line 1, in <module>

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 <module>

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 应用程序。

加载中
返回顶部
顶部