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

 

 

 

©️2020 CSDN 皮肤主题: 数字20 设计师: CSDN官方博客 返回首页
实付0元
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值