当前位置: 移动技术网 > IT编程>开发语言>C/C++ > Windows系统Python直接调用C++ DLL

Windows系统Python直接调用C++ DLL

2019年08月01日  | 移动技术网IT编程  | 我要评论

他们的世界国语版,恶魔法则全文下载,奥德加德

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

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网