python调用dll

调用CALLBACK标记的dll方法要用dll = ctypes.windll.LoadLibrary( 'test.dll' )

没有CALLBACK的方法用dll = ctypes.cdll.LoadLibrary( 'test.dll' )

例子:

from ctypes import *
d2d = cdll.LoadLibrary("Direct2dDll.dll")
print(d2d.DCreateWindow)

CALLBACK = CFUNCTYPE(c_int,c_int)

def py_cmp_func(a):
    print(str(a))
    return 0;
    
callBackFunc = CALLBACK(py_cmp_func)

d2d.SetCallBack(callBackFunc)
d2d.DCreateWindow()
// Direct2dDll.cpp : 定义 DLL 应用程序的导出函数。
//

#include "stdafx.h"
#include <Windows.h>
#include <stdio.h>
#include "Draw.h"

int (*CallBack)(int);

void SetCallBack(int (*fun)(int))
{
    (*fun)(0);
    CallBack = fun;
}

//
//  函数: WndProc(HWND, UINT, WPARAM, LPARAM)
//
//  目的: 处理主窗口的消息。
//
//  WM_COMMAND    - 处理应用程序菜单
//  WM_PAINT    - 绘制主窗口
//  WM_DESTROY    - 发送退出消息并返回
//
//
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    (*CallBack)((int)message);
    int wmId, wmEvent;
    PAINTSTRUCT ps;
    HDC hdc;

    switch (message)
    {
    case WM_PAINT:
        hdc = BeginPaint(hWnd, &ps);
        // TODO: 在此添加任意绘图代码...
        EndPaint(hWnd, &ps);
        break;
    case WM_DESTROY:
        PostQuitMessage(0);
        break;
    default:
        return DefWindowProc(hWnd, message, wParam, lParam);
    }
    return 0;
}

HWND DCreateWindow()
{
    HINSTANCE instance = GetModuleHandle(0);

    TCHAR szWindowClass[] = L"pw";            // 主窗口类名

    WNDCLASSEX wcex;

    wcex.cbSize = sizeof(WNDCLASSEX);
    printf("2");
    wcex.style            = CS_HREDRAW | CS_VREDRAW;
    wcex.lpfnWndProc    = WndProc;
    wcex.cbClsExtra        = 0;
    wcex.cbWndExtra        = 0;
    wcex.hInstance        = instance;
    wcex.hIcon            = 0;//LoadIcon(hInstance, MAKEINTRESOURCE(IDI_WIN32PROJECT1));
    wcex.hCursor        = LoadCursor(NULL, IDC_ARROW);
    wcex.hbrBackground    = (HBRUSH)(COLOR_WINDOW+1);
    wcex.lpszMenuName    = 0;//MAKEINTRESOURCE(IDC_WIN32PROJECT1);
    wcex.lpszClassName    = szWindowClass;
    wcex.hIconSm        = 0;//LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL));

    RegisterClassEx(&wcex);
    printf("3");
    HWND hWnd = CreateWindow(szWindowClass, L"title", WS_OVERLAPPEDWINDOW,
                  CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, NULL, NULL, instance, NULL);
    printf("4");
    ShowWindow(hWnd, SW_MAXIMIZE);
    UpdateWindow(hWnd);

       
    MSG msg;
    // 主消息循环:
    while (GetMessage(&msg, NULL, 0, 0))
    {
        if (!TranslateAccelerator(msg.hwnd, 0, &msg))
        {
            TranslateMessage(&msg);
            DispatchMessage(&msg);
        }
    }

    return hWnd;
}
原文地址:https://www.cnblogs.com/wangjixianyun/p/3416315.html