如何使用python ctypes定义未定义的符号

时间:2018-01-17 19:45:16

标签: python linker shared-libraries ctypes extern

我想使用一个共享库(使用python ctypes),它希望在使用这个共享库的程序中定义一些符号。

在以下示例中,var中定义了test.c,而nm libadd.so显示var未定义;

/* libadd.c */
#include <stdio.h>

extern int var;

int add(int a, int b) {
    return (a + b + var);
}
gcc -c -Wall -Werror -fpic libadd.c
gcc -shared -o libadd.so libadd.o
/* test.c */
#include <stdio.h>
#include "libadd.h"

int var = 1;

int main(void) {
    printf("%d", add(1,2));
    return 0;
}
gcc -L/path/to/libadd -Wall -o test test.c -ladd

同样,如何使用python ctypes执行此操作;

# test.py
from ctypes import *

#what to do to define var?

sharedlib = CDLL("sharedlib/libadd.so", mode = RTLD_GLOBAL)
print( sharedlib.add(1,2) )
OSError: sharedlib/libadd.so: undefined symbol: var

1 个答案:

答案 0 :(得分:2)

一种可能性是创建一个单独的共享库来定义select a.accepter_id, (SELECT COUNT(*) FROM request_accepted ac WHERE ac.accepter_id = a.accepter_id) AS accept_cnt, b.requester_id, (SELECT COUNT(*) FROM request_accepted bc WHERE bc.requester_id = b.requester_id) AS request_cnt from request_accepted a left join request_accepted b on a.accepter_id = b.requester_id GROUP BY a.accepter_id, b.requester_id 并在var之前加载它。

libadd.so
/* resolve.c */
int var = 1;
gcc -c -Wall -Werror -fpic resolve.c
gcc -shared -o resolve.so resolve.o