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

 

posted @   emanlee  阅读(757)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
历史上的今天:
2020-01-19 Thinkpad X220安装SATA接口固态硬盘SSD
2019-01-19 CentOS7设置定时任务 每隔30分钟执行一次命令
2017-01-19 R语言 ggplot2 画平滑图
2015-01-19 mysql查询结果输出到文件
2013-01-19 Java获取当前路径
2010-01-19 System.OutOfMemoryException error thrown when running ReportViewer
点击右上角即可分享
微信分享提示