Python笔记-使用cython生成dll,C++进行调用

这里就是把python改成cython语法,然后使用cython跑下,生成.h和.cpp然后通过python下的lib,以及so文件,以及include生成对应的dll,然后用c++调用即可:

 

如下:

cimport win32api
cimport win32gui

cdef 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 = 10
	win32api.GetCursorPos()
	return int(x)

如果这样编译:

cython CursorPy.pyx

提示pxd是不存中的,目前再cpython中存在的pxd有:

目前只能将其去掉

#cimport win32api
#cimport win32gui

cdef 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 = 10
	win32api.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

 

 

 

猜你喜欢

转载自blog.csdn.net/qq78442761/article/details/107653293