ctypes:获取c函数的实际地址

ctypes: get the actual address of a c function

这很棘手(至少对我来说 :-) ,也许不可行。但我试着问你。

我有这个 C 共享库:

#include <stdio.h>
#include <stdlib.h>

static int variable = -666;

int get_value() {
    return variable;
}

void print_pointer_to_get_value() {
    printf("pointer_to_get_value: %p\n", &get_value);
}

以这种方式编译(在 Linux 上):

gcc -fPIC -c -O2 shared.c && gcc -shared -o shared.so shared.o

现在我加载库并调用 print_pointer_to_get_value():

>>> import ctypes
>>> so = ctypes.cdll.LoadLibrary('./shared.so')
>>> so.print_pointer_to_get_value()
pointer_to_get_value: 0x7f46e178f700

我想从 ctypes 中获取由 print_pointer_to_get_value() 打印的 get_value 函数的实际地址,作为整数。 我的最终目标是将该地址移动到 Cython 模块并在 "nogil" Cython 函数中调用该函数。我需要在运行时加载 .so 库,因此我无法编译链接到库的 Cython 模块。

谢谢 1000。

这是一个讨厌的多步骤过程,不容易优雅地完成:

一些 Cython 代码:

ctypedef double (*math_function_t)(double) nogil

import ctypes

def call_f(f, double x):
    cdef math_function_t cy_f_ptr = (<math_function_t*><size_t>ctypes.addressof(f))[0]

    cdef double res
    with nogil:
        res = cy_f_ptr(x)
    return res

这里我给Cython传了一个Ctypes的函数类型(f),得到了Cython中的地址。我认为不可能获得Python中的地址。作为如何初始化 f 的示例,您可以在 Linux 上执行以下操作:

lib = ctypes.cdll.LoadLibrary("libm.so.6")
f = lib.sin

call_f(f,0.5) # returns sin(0.5)

(使用标准库sin函数)。

Cython 线 cdef math_function_t cy_f_ptr = (<math_function_t*><size_t>ctypes.addressof(f))[0] 可以分解如下:

  1. ctypes.addressof(f) 获取保存 ctypes 变量 f 的地址。__This 不是您想要的值_ - 它是值所在的位置你想要的已被储存。
  2. 这首先转换为 size_t 整数,然后转换为指向 cdef 函数指针类型的指针。 Cython 需要两步转换。
  3. [0] 取消引用您的 math_function_t* 以获得 math_function_t。这是函数指针(即你想要的值)

此答案的信息来自 this newsgroup thread(我目前无法访问)