このページの2つのバージョン間の差分を表示します。
次のリビジョン | 前のリビジョン | ||
shlib [2010/06/26 15:36] – 作成 Takuya Nishimoto | shlib [Unknown date] (現在) – 外部編集 (Unknown date) 127.0.0.1 | ||
---|---|---|---|
行 1: | 行 1: | ||
====== 動的ライブラリ ====== | ====== 動的ライブラリ ====== | ||
- | [[c_language|C言語]](gcc)で動的ライブラリを実装し、C言語および[[Python]]言語から呼び出す例を示す。 | + | [[c_language|C言語]](gcc)で動的ライブラリ(shlib)を実装し、C言語および[[Python]]言語から呼び出す例を示す。 |
- | < | + | 資料 |
- | #! shlibtest | + | * http:// |
+ | * http:// | ||
+ | |||
+ | [[cygwin]] gcc 4.3.4 および python 2.5.2 で動作を確認した。 | ||
+ | |||
+ | < | ||
+ | # Makefile | ||
target: libmystuff main | target: libmystuff main | ||
行 16: | 行 22: | ||
main: main.c | main: main.c | ||
gcc main.c -o main -ldl | gcc main.c -o main -ldl | ||
- | < | + | </code> |
+ | |||
+ | <code c> | ||
+ | /* a.c */ | ||
+ | int a(int x, int y) | ||
+ | { | ||
+ | return x + y; | ||
+ | } | ||
+ | </ | ||
+ | |||
+ | <code c> | ||
+ | /* b.c */ | ||
+ | int b(int x, int y) | ||
+ | { | ||
+ | return x - y; | ||
+ | } | ||
+ | </ | ||
+ | |||
+ | <code c> | ||
+ | /* str.c */ | ||
+ | #include < | ||
+ | |||
+ | char *cat(char *a, char *b) | ||
+ | { | ||
+ | return strcat(a, b); | ||
+ | } | ||
+ | </ | ||
+ | |||
+ | |||
+ | <code c> | ||
+ | /* main.c */ | ||
+ | #include < | ||
+ | #include < | ||
+ | #include < | ||
+ | #include < | ||
+ | |||
+ | int main(void) | ||
+ | { | ||
+ | void *handle; | ||
+ | int (*func_a)(int, | ||
+ | int (*func_b)(int, | ||
+ | char *(*func_cat)(char *, char *); | ||
+ | char *error; | ||
+ | char buf1[10], buf2[10]; | ||
+ | |||
+ | handle = dlopen(" | ||
+ | if (!handle) { | ||
+ | fputs (dlerror(), stderr); | ||
+ | exit(1); | ||
+ | } | ||
+ | |||
+ | func_a = dlsym(handle, | ||
+ | if ((error = dlerror()) != NULL) { | ||
+ | fputs(error, | ||
+ | exit(1); | ||
+ | } | ||
+ | |||
+ | func_b = dlsym(handle, | ||
+ | if ((error = dlerror()) != NULL) { | ||
+ | fputs(error, | ||
+ | exit(1); | ||
+ | } | ||
+ | |||
+ | func_cat = dlsym(handle, | ||
+ | if ((error = dlerror()) != NULL) { | ||
+ | fputs(error, | ||
+ | exit(1); | ||
+ | } | ||
+ | |||
+ | printf(" | ||
+ | printf(" | ||
+ | |||
+ | strcpy(buf1, | ||
+ | strcpy(buf2, | ||
+ | printf(" | ||
+ | dlclose(handle); | ||
+ | return 0; | ||
+ | } | ||
+ | </ | ||
+ | <code python> | ||
+ | # main.py | ||
+ | from ctypes import * | ||
+ | h = cdll.LoadLibrary(" | ||
+ | print h.a(3,2) | ||
+ | print h.b(3,2) | ||
+ | s1 = create_string_buffer(' | ||
+ | print c_char_p(h.cat(s1,' | ||
+ | </ | ||