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

yipeiwu_com5年前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设计】网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!

相关文章

详解在Python和IPython中使用Docker

现在Docker是地球上最炙手可热的项目之一,就意味着人民实际上不仅仅是因为这个才喜欢它。 话虽如此,我非常喜欢使用容器,服务发现以及所有被创造出的新趣的点子和领域来切换工作作为范例。...

把MySQL表结构映射为Python中的对象的教程

ORM mysql的表结构是二维表,用python的数据结构表示出来就是一个列表,每一个记录是一个tuple。如下所示: [('1', ''huangyi),('2', ''letian...

python自动截取需要区域,进行图像识别的方法

实例如下所示: import os os.chdir("G:\Python1\Lib\site-packages\pytesser") from pytesser import *...

Python实现的基数排序算法原理与用法实例分析

Python实现的基数排序算法原理与用法实例分析

本文实例讲述了Python实现的基数排序算法。分享给大家供大家参考,具体如下: 基数排序(radix sort)属于“分配式排序”(distribution sort),又称“桶子法”(...

Python中zfill()方法的使用教程

 zfill()方法用零垫串来填充左边宽度。 语法 以下是zfill()方法的语法: str.zfill(width) 参数    ...