如何正确转换 c 数据类型?

问题描述 投票:0回答:0

我在 python 中使用 c 函数时遇到问题。

我尝试了一些适用于 Linux 的简单示例:

我的 C 代码示例:

void hello_world(){
    printf("hello world\n");
}

double calculate_square(int number){
    double square = 0;

    for (int i = 0; i < number; i++){
        square = square + i * number;
    }
    return square;
}

我正在制作一个 .so 文件并尝试在 Python 中使用 c 函数:

if platform.system() == 'Linux':
    from ctypes import cdll
    import os

    dirname = os.path.dirname(__file__)
    liblocation = os.path.join(dirname, 'functions.so')
    lib = cdll.LoadLibrary((liblocation))
    lib.hello_world()
    print(lib.calculate_square(30))
    lib.calculate_square.restype = ctypes.c_double
    lib.calculate_square.argtype = [ctypes.c_int]
    print(lib.calculate_square(30))

这是输出:

hello world
30
900.0

为了使函数正常工作,将参数和返回值的数据类型转换为 ctypes 数据类型很重要。可以看到,

calculate_square
先返回30,转换数据类型后,返回正确结果900。

现在我必须在以下 C 代码片段上实现这些知识(C 代码应该是正确的,因为在 32 位 Windows 下一切正常):

jtag_core * jtagcore_init()
{
    jtag_core * jc;
    script_ctx * sctx;

    jc = (jtag_core *)malloc(sizeof(jtag_core));
    if ( jc )
    {
        memset( jc, 0, sizeof(jtag_core) );

        jtagcore_setEnvVar( jc, "LIBVERSION", "v"LIB_JTAG_CORE_VERSION);

        sctx = jtagcore_initScript(jc);

        jtagcore_execScriptRam( sctx, config_script, config_script_len );

        jtagcore_execScriptFile( sctx, "config.script" );

        jtagcore_deinitScript(sctx);
    }

    return jc;
}

为此,有一个 Python 类:

class JTAGCore(object):

    def __init__(self):
        if platform.system() == 'Linux':
            from ctypes import cdll
            import os

            dirname = os.path.dirname(__file__)
            liblocation = os.path.join(dirname, "libjtag_core.so")
            self.lib = cdll.LoadLibrary(liblocation)

        self._print_callback = CFUNCTYPE(None, POINTER(c_char))(self._loggingprint)
        self._jtag = self.lib.jtagcore_init()
        self.lib.jtagcore_set_logs_callback(self._jtag, self._print_callback)

interface = JTAGCore()

这给了我这个输出:

Process finished with exit code 139 (interrupted by signal 11: SIGSEGV)

有人知道如何让它运行吗?

python c ctypes
© www.soinside.com 2019 - 2024. All rights reserved.