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

相关文章

mac安装pytorch及系统的numpy更新方法

安装Pytorch 在pytorch官网上选择相应选项,我的是OS X, pip, python2.7, none CUDA。 (之所以用python2.7只是觉得现在还有好多代码用2....

Python多进程入门、分布式进程数据共享实例详解

本文实例讲述了Python多进程入门、分布式进程数据共享。分享给大家供大家参考,具体如下: python多进程入门 https://docs.python.org/3/library/m...

python增加图像对比度的方法

本代码实现的是,在旋转10度的基础上,再进行增加对比度的操作。 1 代码: 代码注释中的代码都是可以运行的.  但是不怎么靠谱,因为文件名被逐个编辑,有可能与原标签不对应,,更...

Python实现中一次读取多个值的方法

Python实现中一次读取多个值的方法

Python 2里面读取输入的函数是raw_input(), Python 3的是input(),读入一个值后回车读取输入就退出了,想要一次读取多个输入,可以像下面这样: a, b...

python计算最小优先级队列代码分享

复制代码 代码如下:# -*- coding: utf-8 -*- class Heap(object):     @classmethod &n...