关于Python调用C++库

C语言 码拜 8年前 (2016-05-29) 1166次浏览
a.cpp生成一个a.so库文件,
现在在b.py文件中的一个函数中加载a.so,
a.cpp中有一个函数func()和一个全局变量g_val;
b.py中的一个函数循环调用func()这个函数,func()这个函数就是向g_val这个变量中Push值,
那么问题来了,经过b.py中100次循环调用func()这个函数,g_val中能否也对应的有100个值呢?
意思就是想问:
对于Python来说,加载的C++库假如存在全局变量,那么这个全局变量相对于Python来说是不是也是全局变量呢?
解决方案

40

是的。

    //test.cpp
  1 #include <vector>
  2 #include <stdio.h>
  3 using namespace std;
  4 
  5 vector<int> g_vecVar;
    int g = 1;
  6 extern "C"
  7 {
  8         void func()
  9         {
               g++;
 10          g_vecVar.push_back(g);
 11 
 12         for( int i = 0; i < g_vecVar.size() ;i++ )
 13          printf( "%d\n", g_vecVar.at(i));
 14         }
 15 }

g++ test.cpp -fPIC -shared test.so

  1 # -*- encoding: utf-8 -*-
  2 
  3 import os
  4 import ctypes
  5 
  6 class test():
  7     def __init__(self,):
  8         self.lib_handle = ctypes.CDLL("./test.so")
  9         self.testfunc = self.lib_handle.func
 10 
 11 
 12 if __name__ == "__main__":
 13     mytest = test();
 14     for i in range(10):
 15         mytest.testfunc();

执行python代码,输出结果为
2
2
3
2
3
4
2
3
4
5
.
.
.
.
.
.


CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明关于Python调用C++库
喜欢 (0)
[1034331897@qq.com]
分享 (0)