python怎么调用c++dll_Windows系统Python直接调用C++ DLL的方法

环境: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

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的方法,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对脚本之家网站的支持!

如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值