c/c++语言开发共享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; …

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

 1 #pragma once   2    3 #ifndef cpp_exports   4 #define cpp_exports   5 #endif   6    7 #ifdef cpp_exports   8 #define cpp_api _declspec(dllexport)   9 #else   10 #define cpp_api _declspec(dllimport)  11 #endif  12   13 #include <iostream>  14 using namespace std;  15   16 #ifdef __cplusplus  17 extern "c"  18 {  19 #endif  20   21     cpp_api int __cdecl getint();  22     cpp_api const char* __cdecl getstring();  23     cpp_api void __cdecl setstring(const char* str);  24   25 #ifdef __cplusplus  26 }  27 #endif

 

example.cpp

 1 #include "pch.h"   2 #include "example.h"   3    4 cpp_api int __cdecl getint()   5 {   6     return 5;   7 }   8    9 cpp_api const char* __cdecl getstring()  10 {  11     return "hello";  12 }  13   14 cpp_api void __cdecl setstring(const char* str)  15 {  16     cout << str << endl;  17 }

 

编译,得到 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

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/c-cdevelopment/602482.html

(0)
上一篇 2021年5月11日
下一篇 2021年5月11日

精彩推荐