Python과 DLL 사이에서의 interface방법에 대해 알아보자. DLL interface는 확장 DLL이 아닌 Generic DLL만 다룬다. 
simple interface
C part
아래 코드를 이용하여 dll을 만든다.
#include <stdio.h>

extern "C" _declspec(dllexport) int testDLL(void);

int testDLL(void)
{
    printf("Hello world\n");
    return 1;
};

python에서는 ctype을 사용하여 DLL을 load한 후 call하면 된다. 
from ctypes import *
dll = cdll.LoadLibrary('debug/ssdll.dll')
dll.testDLL()

hello world가 출력됨을 확인할 수 있다. 위의 내용이 visual C++ 파일로 첨부되어 있다.

Argument 전달
처음의 예는 argument 없이 함수 call만 하였는데 인자를 전달해 보자. 인자는 python에서 c_double(), c_int(), c_char_p(), c_long()을 사용하여 전달하면 된다. 
int testDLL2(int a, float b)
{
    return int(a + b);
}   
int testDLL3(char *p)
{
    printf(p);
    return 1;
};

# python
print dll.testDLL2(c_int(3),c_float(5.7))
dll.testDLL3(c_char_p('Hello from python'))

참고로 integer나 char pointer인 경우 c_int(), c_char_p()를 생략해도 된다. 


callback 함수 
python에서 DLL에 있는 함수를 call 할 수 있고, 또한 C에서 python 쪽의 함수를 call하거나 변수의 값을 읽어들일 수 있다. 
이것에 대해서는 첨부된 파일을 참조하면 별다는 어려움없이 이해할 수 있으리라 생각된다. 

첨부된 파일은 Visual C++ 2008 express version으로 작성되었다.



+ Recent posts