Windows系统Python直接调用C++ DLL的方法

yipeiwu_com6年前Python基础

环境:Window 10,VS 2019, Python 2.7.12, 64bit

1,打开 VS 2019,新建C++ Windows 动态链接库工程 Example,加入下列文件,如果Python是64位的则在VS中 Solution platforms 选择 x64 编译成64位的 DLL;

Example.h

#pragma once
#ifndef CPP_EXPORTS
#define CPP_EXPORTS
#endif
#ifdef CPP_EXPORTS
#define CPP_API _declspec(dllexport)
#else 
#define CPP_API _declspec(dllimport)
#endif
#include <iostream>
using namespace std;
#ifdef __cplusplus
extern "C"
{
#endif
  CPP_API int __cdecl getInt();
  CPP_API const char* __cdecl getString();
  CPP_API void __cdecl setString(const char* str);
#ifdef __cplusplus
}
#endif

Example.cpp

#include "pch.h"
#include "Example.h"
CPP_API int __cdecl getInt()
{
  return 5;
}
CPP_API const char* __cdecl getString()
{
  return "hello";
}
CPP_API void __cdecl setString(const char* str)
{
  cout << str << endl;
}

编译,得到 Example.dll

2, 打开 Command,cd 到 Example.dll 所在目录,输入 Python2,进入python环境

>>> from ctypes import *
>>> dll = CDLL("Example.dll")
>>> print dll.getInt()
5
>>> getStr = dll.getString
>>> getStr.restype = c_char_p
>>> pChar = getStr()
>>> print c_char_p(pChar).value
hello
>>> setStr = dll.setString
>>> setStr.argtypes = [c_char_p]
>>> pStr = create_string_buffer("hello")
>>> setStr(pStr)
hello
-1043503984

总结

以上所述是小编给大家介绍的Windows系统Python直接调用C++ DLL的方法,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对【听图阁-专注于Python设计】网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!

相关文章

django 类视图的使用方法详解

 前言 当我们在开发一个注册模块时。浏览器会通过get请求让注册表单弹出来,然后用户输完注册信息后,通过post请求向服务端提交信息。这时候我们后端有两个视图函数,一个处理ge...

Python3.5面向对象与继承图文实例详解

Python3.5面向对象与继承图文实例详解

本文实例讲述了Python3.5面向对象与继承。分享给大家供大家参考,具体如下: 1、编程的方式 2、面向对象的基本概念 3、类的基本概念 4、类的定义与调...

通过代码实例展示Python中列表生成式的用法

1 平方列表 如果你想创建一个包含1到10的平方的列表,你可以这样做: squares = [] for x in range(10): squares.append(x**2)...

Python使用pip安装pySerial串口通讯模块

Python使用pip安装pySerial串口通讯模块

pySerial封装了对串口的访问,供大家参考,具体内容如下 特性 在支持的平台上有统一的接口。 通过python属性访问串口设置。 支持不同的字节大小、停止位、校验位和流控设置。 可...

numpy数组做图片拼接的实现(concatenate、vstack、hstack)

两种方法拼接 #img = np.vstack((img, img2)) # vstack按垂直方向,hstack按水平方向 img = np.concatenate((img,...