第一种、Python调用C动态链接库(利用ctypes)
下面示例在linux或unix下可行。
pycall.c
1
2
3
4
5
6
7
8
|
#include <stdlib.h>
int foo( int a, int b)
{
printf ( "you input %d and %d\n" , a, b);
return a+b;
}
|
pycall.py
1
2
3
4
5
|
import ctypes
ll = ctypes.cdll.LoadLibrary
lib.foo( 1 , 3 )
print '***finish***'
|
运行方法:
gcc -o libpycall.so -shared -fPIC pycall.c
python pycall.py
第2种、Python调用C++(类)动态链接库(利用ctypes)
pycallclass.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
#include <iostream>
using namespace std;
class TestLib
{
public :
};
void TestLib::display() {
}
void TestLib::display( int a) {
cout<< "Second display:" <<a<<endl;
}
extern "C" {
TestLib obj;
}
}
}
|
pycallclass.py
1
2
3
4
5
6
7
|
import ctypes
so = ctypes.cdll.LoadLibrary
|
运行方法:
g++ -o libpycallclass.so -shared -fPIC pycallclass.cpp
python pycallclass.py
第3种、Python调用C和C++可执行程序
main.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
#include <iostream>
using namespace std;
{
int a = 10, b = 5;
return a+b;
}
int main()
{
cout<< "---begin---" <<endl;
cout<< "num=" <<num<<endl;
cout<< "---end---" <<endl;
}
|
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
import commands
import os
main = "./testmain"
rc, out = commands.getstatusoutput(main)
print 'rc = %d, \nout = %s' % (rc, out)
print '*' * 10
f = os.popen(main)
f.close()
print data
print '*' * 10
|
运行方法(只有这种不是生成.so然后让python文件来调用):
g++ -o testmain main.cpp
python main.py
疑问:
Windows 如何实现?
REF
https://www.jb51.net/article/165362.htm
https://www.cnblogs.com/si-lei/p/10748612.html
https://www.cnblogs.com/fyly/p/11266308.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。