Skip to content

Instantly share code, notes, and snippets.

@peace098beat
Created June 25, 2015 08:02
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save peace098beat/7837b71b83e5476e1cc1 to your computer and use it in GitHub Desktop.
Save peace098beat/7837b71b83e5476e1cc1 to your computer and use it in GitHub Desktop.
[Python] PythonでC言語のDLLを呼び出す その1
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void printdll(int * a_ary, int a_ary_length) {
int i;
for (i = 0; i < a_ary_length; i++) {
printf("a_ary[%d] = %d\n", i, a_ary[i]);
a_ary[i] = a_ary[i]*a_ary[i];
}
}

dllの作り方

# dll化するコードをコンパイル
$ gcc -c dylibexample.c
>> dylibexample.c dylibexample.o
 
# -sharedオプションをつけてdllに変換
$ gcc -shared -o dylibexample.dll dylibexample.c
>> dylibexample.dll
 
# コンパイル時にダイナミックリンクライブラリ(dylibexample.dll)をリンク
$ gcc -I./ -L./ -o main.exe main.c -ldylibexample
 
$ ./main.exe
>> Hello!

pythonでの呼び出し

userdll = windll.LoadLibrary('dylibexample.dll')
userdll.hello()
# coding: utf-8
# ***************************************************
#
# main.py
# dllの呼び出し確認用コード
#
# ***************************************************
from ctypes import *
# 標準dllの呼び出し(テスト)
# cdll.msvcrt.printf('Hello, world!\n')
# cdll.msvcrt.printf('double value: %f\n', c_double(3.14))
# 自作dllの呼び出し
userdll = windll.LoadLibrary('rcadll.dll')
# 定数
FRAME_SIZE = 10
# 配列のオブジェクトを作成する
# C言語で言うならば、array_aype = (int*)malloc(sizeof(int) * FRAME_SIZE)
ArrayType = c_int * FRAME_SIZE
ary = ArrayType()
# 作成した配列に値を入れる
for i, val in enumerate(ary):
ary[i] = i
# 自作のdllを呼び出す(値を2乗する関数)
# ポインタを渡している格好になる.
userdll.printdll(ary, FRAME_SIZE)
# 戻ってきた配列の中身を見る
for i, val in enumerate(ary):
print i, val
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment