#include <windows.h> #include <cstdio> #if defined(_WIN32) #define DLL_EXPORT extern "C" __declspec(dllexport) #else #define DLL_EXPORT extern "C" #endif
DLL_EXPORT double squared(double* a) { return *a * *a; }
DLL_EXPORT void squared(double* a) { *a = *a * *a; }
DLL_EXPORT float add_values(int a, float b) { return a + b; }
DLL_EXPORT void get_version(char* const out_buf) { const char* text = "Version 1.0.0"; int len = strlen(text); if (out_buf != NULL) { strcpy(out_buf,text); } }
// 定数を返す DLL_EXPORT int get_constant_value() { return 42; }
// メッセージを標準出力に表示 DLL_EXPORT void print_message() { printf("Hello World\n"); }
BOOL APIENTRY DllMain( HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved ) { switch (ul_reason_for_call) { case DLL_PROCESS_ATTACH: case DLL_THREAD_ATTACH: case DLL_THREAD_DETACH: case DLL_PROCESS_DETACH: break; } return TRUE; }
import ctypes from ctypes import c_int, c_float,c_double, c_size_t, c_char_p, POINTER, create_string_buffer dll = ctypes.CDLL(r".\sample.dll") # # void squared(double* a) # dll.squared.argtypes = (ctypes.POINTER(c_double),) # 引数の型指定 dll.squared.restype = None # 戻り値の型指定 v = c_double(3.0) # Cの double 型の変数作成 dll.squared(ctypes.byref(v)) # 関数呼び出し , ポインタ渡し ret = v.value # 結果取得 print("squared result:", ret) # 結果表示 # # float add_values(int a, float b) # dll.add_values.argtypes = (c_int, c_float) # 引数の型指定 dll.add_values.restype = c_float # 戻り値の型指定 ret = dll.add_values(10, c_float(2.5)) print("add_values:", ret) # # void get_version(char* out_buf) # dll.get_version.argtypes = (ctypes.c_char_p,) # 引数の型指定 dll.get_version.restype = None # 戻り値の型指定 buf = create_string_buffer(64) # 文字列を受け取るためのバッファ作成 dll.get_version(buf) # 関数呼び出し , ポインタ渡し ret = buf.value.decode("utf-8") # 結果取得 print("version:", ret) # # int get_constant_value() # dll.get_constant_value.argtypes = () # 引数なし dll.get_constant_value.restype = c_int # 戻り値の型指定 ret = dll.get_constant_value() print("constant:", ret) # # void print_message() # dll.print_message.argtypes = () # 引数なし dll.print_message.restype = None # 戻り値なし dll.print_message() # 関数呼び出し