cython 段错误处理

标签 c exception-handling segmentation-fault cython

我正在包装一些 C 库,并且我有一个函数在某些情况下可能会导致段错误。在那种情况下,我需要调用第二个函数,它会在那种情况下成功完成。

有谁知道如何处理 cython 中的段错误?

最佳答案

一个可能有帮助的简短示例(使用 signal):

example.h(假设 Cython 扩展名为 myext.pyx)

// Header autogenerated by Cython when declaring "public api" functions
#include "../myext_api.h"  

void handleFuncFailure(char *func1_name, char *func2_name);
void generateSegFault();

example.c

#include <example.h>
#include <signal.h>

static char *func2name;

static void handler2(int sig)
{
    // Catch exceptions
    switch(sig)
    {
        case SIGSEGV:
            fputs("Caught SIGSEGV: segfault !!\n", stderr);
            break;
    }
    int error;
    // "call_a_cy_func()" is provided by "myext.pyx"
    call_a_cy_func(func2name, &error);
    exit(sig);
}

void handleFuncFailure(char *func1_name, char *func2_name) {

    // Provided by autogenerated "myext_api.h" header
    import_myext();

    func2name = func2_name;
    signal(SIGSEGV, handler2);
    int error;
    // "call_a_cy_func()" is provided by "myext.pyx"
    call_a_cy_func(func1_name, &error);
}

void generateSegFault() {
    *(int*) 0 = 0;
}

myext.pyx

# Helper function to call a function by its name
# "public api" enables to call this function from C side (See above)
cdef public api void call_a_cy_func(char* method, bint *error):
    if (method in globals()):
        error[0] = 0
        globals()[method]();
    else:
        error[0] = 1

# Expose C functions
cdef extern from "src/example.h":
    void handleFuncFailure(char *func1_name, char *func2_name)
    void generateSegFault()

# The unreliable function
def func1():
    print "hello1 ! Generating segfault..."
    generateSegFault()

# The reliable function
def func2():
    print "hello2 ! Running safe code..."

# To be called from the Cython extension inner code    
cdef myHandleFuncFailure(f1, f2):
    handleFuncFailure(f1, f2)

# To be called from Python source by importing "myext" module
def myHandleFuncFailure2():
    myHandleFuncFailure("func1", "func2")

输出

hello1 ! Generating segfault...

Caught SIGSEGV: segfault !!

hello2 ! Running safe code...

我希望这能提供一些想法,至少...

关于cython 段错误处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17435656/

相关文章:

c - MIPS的堆栈让我脑洞大开

c - 算法分析 -- Big O Notation

java - Java出现未报告的异常

c - 为什么在写入使用字符串文字初始化的 "char *s"而不是 "char s[]"时出现段错误?

带有任何参数的 C++ 函数会导致段错误

c - 我如何测试我的程序是否正在存储信息或覆盖它

c - 在 MSP430 上进行 SPI 轮询读/写?

python - 如何在 Python 中正确获取异常消息

groovy - Geb 的一般问题(StaleElementReferenceException 和等待超时)

c - ./geany_run_script.sh : Segmentation fault