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实现的解析crontab配置文件代码

#/usr/bin/env python #-*- coding:utf-8 -*- """ 1.解析 crontab 配置文件中的五个数间参数(分 时 日 月 周),获取他们对...

利用Django模版生成树状结构实例代码

利用Django模版生成树状结构实例代码

前言 我们经常会有这样的需求,比如评论功能,每个评论都有可能会有自己的子评论,如果在界面只展示成一列的话非常不美观,也不能体现出他们的层级关系。那么我们今天就来看看如何使用Django的...

python机器学习实现决策树

python机器学习实现决策树

本文实例为大家分享了python机器学习实现决策树的具体代码,供大家参考,具体内容如下 # -*- coding: utf-8 -*- """ Created on Sat Nov...

python lambda表达式在sort函数中的使用详解

1.lambda表达式一般用法 语法: lamda argument:expression example: add = lambda x, y: x+y print(add(10,...

Python对文件操作知识汇总

打开文件 操作文件 1打开文件时,需要指定文件路径和打开方式 打开方式: r:只读 w:只写 a:追加 “+”表示可以同时读写某个文件 r+:读写 w+:写读 a+:同a U"表示在读取...