Python笔记-使用cython生成dll,C++进行调用
生活随笔
收集整理的這篇文章主要介紹了
Python笔记-使用cython生成dll,C++进行调用
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
這里就是把python改成cython語法,然后使用cython跑下,生成.h和.cpp然后通過python下的lib,以及so文件,以及include生成對應的dll,然后用c++調用即可:
?
如下:
cimport win32api cimport win32guicdef public int getCursorPosX():x, y = win32api.GetCursorPos()return int(x)cdef public int getCursorPosY():x, y = win32api.GetCursorPos()return int(y)cdef public int test():x = 10;return int(x)cdef public int test2():x = 10win32api.GetCursorPos()return int(x)如果這樣編譯:
cython CursorPy.pyx提示pxd是不存中的,目前再cpython中存在的pxd有:
目前只能將其去掉
#cimport win32api #cimport win32guicdef public int getCursorPosX():x, y = win32api.GetCursorPos()return int(x)cdef public int getCursorPosY():x, y = win32api.GetCursorPos()return int(y)cdef public int test():x = 10;return int(x)cdef public int test2():x = 10win32api.GetCursorPos()return int(x)使用下面的命令生成.h和.cpp
cython CursorPy.pyx下面演示下生成dll,vs2015!!創建dll
這里必須用x64的release.
包含項需要:
文件結構如下:
新建
GetCursorPostion.h
#pragma once#include "stdafx.h" #include <Windows.h>#define ExportFunc _declspec(dllexport)extern "C" ExportFunc POINT getCursorPos(); extern "C" ExportFunc int getTest(); extern "C" ExportFunc int getTest2();GetCursorPostion.cpp // GetCursorPosition.cpp : 定義 DLL 應用程序的導出函數。 //#include "stdafx.h" #include "CursorPy.h" #include "GetCursorPosition.h"POINT getCursorPos() {POINT result;result.x = getCursorPosX();result.y = getCursorPosY();return result; }int getTest() {int ret = test();return ret;}int getTest2() {int ret = test2();return ret;}再dll啟動時進行添加:
這里需要調用:
switch (ul_reason_for_call){case DLL_PROCESS_ATTACH:Py_Initialize();PyInit_CursorPy();case DLL_THREAD_ATTACH:case DLL_THREAD_DETACH:case DLL_PROCESS_DETACH:Py_Finalize();break;}其中PyInit_CursorPy()可以在CursorPy.h中找到
然后進行生成好文件:
下面是調用:
源碼如下:
#include <iostream> #include <Windows.h>using namespace std;typedef POINT(*CursorPos)(); typedef int(*Test)(); typedef int(*Test2)();int main() {HMODULE hMoudle = LoadLibrary("D:\\vsproject\\GetCursorPosition\\x64\\Release\\GetCursorPosition.dll");if (!hMoudle) {cout << "loadLibrary failed!" << endl;getchar();return 0;}CursorPos cursorPos;cursorPos = (CursorPos)GetProcAddress(hMoudle, "getCursorPos");Test test = (Test)GetProcAddress(hMoudle, "getTest");Test2 test2 = (Test2)GetProcAddress(hMoudle, "getTest2");while (1) {//POINT point = cursorPos();//cout << "x:" << point.x << " y:" << point.y << endl;cout << test() << endl;//cout << test2() << endl;Sleep(500);}return 0; }源碼打包下載地址:
https://github.com/fengfanchen/CAndCPP/tree/master/pythonDll
?
?
?
總結
以上是生活随笔為你收集整理的Python笔记-使用cython生成dll,C++进行调用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Qt文档阅读笔记-对JSON Save
- 下一篇: Java笔记-对CountDownLat