Python 和 C语言的相互调用

第一种、Python调用C动态链接库(利用ctypes)

下面示例在linux或unix下可行。

pycall.c

1
2
3
4
5
6
7
8
/***gcc -o libpycall.so -shared -fPIC pycall.c*/
#include <stdio.h>
#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 = ll("./libpycall.so"
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 display();
    void display(int a);
};
void TestLib::display() {
  cout<<"First display"<<endl;
}
  
void TestLib::display(int a) {
  cout<<"Second display:"<<a<<endl;
}
extern "C" {
  TestLib obj;
  void display() {
    obj.display(); 
   }
  void display_int() {
    obj.display(2); 
   }
}

pycallclass.py

1
2
3
4
5
6
7
import ctypes
so = ctypes.cdll.LoadLibrary 
lib = so("./libpycallclass.so"
print 'display()'
lib.display()
print 'display(100)'
lib.display_int(100)

运行方法:

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 test()
{
  int a = 10, b = 5;
  return a+b;
}
int main()
{
  cout<<"---begin---"<<endl;
  int num = test();
  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"
if os.path.exists(main):
  rc, out = commands.getstatusoutput(main)
  print 'rc = %d, \nout = %s' % (rc, out)
  
print '*'*10
f = os.popen(main) 
data = f.readlines() 
f.close() 
print data
  
print '*'*10
os.system(main)
 

运行方法(只有这种不是生成.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

原文地址:https://www.cnblogs.com/emanlee/p/15821217.html