我打电话的共享库写成C
的Python/numpy
使用ctypes
。但是,当exit
在C
某些情况下使用该函数时,这会产生奇妙的效果iPython
。
考虑下面的示例,其中在中修改了数组“ A”的第一项C
。如果该值为负,则应引发异常。
-C
代码:
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
extern void cfun(double* A)
{
// raise exception if A[0]<0.0
if ( A[0]<0.0 ) {
printf("Negative value of A[0] encountered\n");
exit(1);
}
// change "A[0]" to it's square
A[0] = pow(A[0],2);
}
使用哪个编译
gcc -c -fPIC fun.c
gcc -shared -o test.so fun.o
包装Python
代码:
import numpy as np
import ctypes
# include shared library
lib = ctypes.CDLL("./test.so")
# link to C-program, including input-typing
cfun = lib.cfun
cfun.restype = None
cfun.argtypes = [ np.ctypeslib.ndpointer(ctypes.c_double,flags="C_CONTIGUOUS") ]
# simple example
A = np.arange((5),dtype='float')+2.
cfun(A)
print A
# expected output: [ 4. 3. 4. 5. 6.]
# simple example
A[0] = -10.0
cfun(A)
print A
# expected output: exception, no output from "print A"
当我从命令行运行此代码时,程序将执行应做的事情。输出:
[ 4. 3. 4. 5. 6.]
Negative value of A[0] encountered
但是当我从运行python函数时 iPython
iPython
存在。我相信最优雅的解决方案是引入错误流作为(返回)参数,以指示成功或失败。但是我真的很想避免这种情况。我使用了广泛的C
-code。引入错误流会使所有功能之间的依赖关系过于复杂。
请帮忙!
exit
调用系统的退出函数并终止运行的进程(在您的情况下为ipython)。在C中进行错误处理的方式是设置一些全局错误变量并返回一个状态标志
#include <math.h>
char *error_string;
extern char* get_error_string() {
return error_string;
}
extern int cfun(double* A)
{
// raise exception if A[0]<0.0
if ( A[0]<0.0 ) {
error_string = "Negative value of A[0] encountered\n";
return -1;
}
// change "A[0]" to it's square
A[0] = pow(A[0],2);
return 0;
}
并在Python中测试错误:
import numpy as np
import ctypes
# include shared library
lib = ctypes.CDLL("./test.so")
# link to C-program, including input-typing
get_error = lib.get_error
get_error.restype = ctypes.c_char_p
get_error.argtypes = []
def c_error_wrapper(func):
def method(*args):
status = func(*args)
if status<0:
raise RuntimeError(get_error())
return method
# link to C-program, including input-typing
cfun = lib.cfun
cfun.restype = ctypes.c_int
cfun.argtypes = [ np.ctypeslib.ndpointer(ctypes.c_double,flags="C_CONTIGUOUS") ]
cfun = c_error_wrapper(cfun)
# simple example
A = np.arange((5),dtype='float')+2.
cfun(A)
print A
# expected output: [ 4. 3. 4. 5. 6.]
# simple example
A[0] = -10.0
cfun(A)
print A
# expected output: exception, no output from "print A"
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句