关于Python调用C++库,该如何处理
关于Python调用C++库
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来说是不是也是全局变量呢?
------解决思路----------------------
是的。
g++ test.cpp -fPIC -shared test.so
执行python代码,输出结果为
2
2
3
2
3
4
2
3
4
5
.
.
.
.
.
.
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来说是不是也是全局变量呢?
------解决思路----------------------
是的。
//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
.
.
.
.
.
.