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生成1行四列全2矩阵的方法

如下所示: print np.ones((1,4))*2 以上这篇python生成1行四列全2矩阵的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听...

python+matplotlib绘制3D条形图实例代码

python+matplotlib绘制3D条形图实例代码

本文分享的实例主要实现的是Python+matplotlib绘制一个有阴影和没有阴影的3D条形图,具体如下。 首先看看演示效果: 完整代码如下: import numpy as n...

详解Python3 对象组合zip()和回退方式*zip

详解Python3 对象组合zip()和回退方式*zip

zip即将多个可迭代对象组合为一个可迭代的对象,每次组合时都取出对应顺序的对象元素组合为元组,直到最少的对象中元素全部被组合,剩余的其他对象中未被组合的元素将被舍弃。 keys =...

对dataframe进行列相加,行相加的实例

实例如下所示: >>> import pandas as pd >>> df = pd.DataFrame({"x":['a','b','c','...

Pytorch模型转onnx模型实例

如下所示: import io import torch import torch.onnx from models.C3AEModel import PlainC3AENetCBA...