Python 使用ctypes从空函数(segfault)x64获取指针

Python 使用ctypes从空函数(segfault)x64获取指针,python,c,ctypes,Python,C,Ctypes,我已将问题归结为以下玩具文件和命令: // a.c --> a.out, compiled with `gcc -fPIC -shared a.c` void* r2() { return NULL; // <-- could be anything } python-i-c “从ctypes导入*; clib=cdll.LoadLibrary('/home/soltanmm/tmp/a.out'); CFUNCTYPE(c_int).in_dll(clib,'r1')()“C

我已将问题归结为以下玩具文件和命令:

// a.c --> a.out, compiled with `gcc -fPIC -shared a.c`
void* r2() {
  return NULL; // <-- could be anything
}
python-i-c
“从ctypes导入*;
clib=cdll.LoadLibrary('/home/soltanmm/tmp/a.out');

CFUNCTYPE(c_int).in_dll(clib,'r1')()“

CFUNCTYPE用于回调(或指向在共享对象中定义为变量的函数的指针)。执行
cdll.LoadLibrary
之后,您应该能够直接调用返回的库对象上的
C
函数。因此,类似这样的方法应该有效:

from ctypes import *;
clib = cdll.LoadLibrary('/home/soltanmm/tmp/a.out');
print(clib.r2())
_dll中的方法
通常用于访问从共享对象导出的变量。它本身不起作用。在_dll
中使用
的示例如下:

文件a.c

#include <stdlib.h>

int r2() {
    return 101;
}

int (*f)(void) = r2;
char *p = "Hello World";

char *gethw() {
    return p;
}

有关ctypes用法的更多信息,请参见

为什么希望0x34是有效的虚拟地址?我不希望。我希望函数返回一个无效地址。我没有去引用它,而且segfault显然发生在FFI调用中,与去引用结果无关。我可以用0替换它,但它仍然会出错。我编辑了这个问题,以表明结果的不相关性。哦,糟糕
a.out
是正确的-我不知道我为什么写
a.so
。我添加了编译命令。等等,那么我在文档中看到的
in_dll
函数是怎么回事?in_dll用于访问从共享对象导出的变量,而不是函数本身。我给出了一个使用CFUNTYPE返回一个变量的例子,该变量是指向函数的指针,然后我调用它!可以不过,我有点奇怪,函数指针和函数符号之间没有等价的处理方法。但是,很酷,谢谢。
#include <stdlib.h>

int r2() {
    return 101;
}

int (*f)(void) = r2;
char *p = "Hello World";

char *gethw() {
    return p;
}
from ctypes import *;
clib = cdll.LoadLibrary('/home/soltanmm/tmp/a.out');

# print should call r2() since f is a variable initialized to
# point to function r2 that returns an int. Should 
# print 101
print (CFUNCTYPE(c_int).in_dll(clib,'f')())

# or call r2 directly
print(clib.r2())

# prints out the character (char *) string variable `p'
# should result in 'Hello World' being printed.
print((c_char_p).in_dll(clib,'p').value)

# call the gethw() function that returns a point to a char *
# This too should print 'Hello World'
# we must set the restype c_char_p explicitly since the default
# is to assume functions return `int`
gethw = clib.gethw
gethw.restype = c_char_p
print(gethw())